COMP 183 QUIZ #1

October 31st, 2011

Time: 90 minutes

ANSWER KEY

QUESTION 1 (50 points)

The roots of the quadratic equation are given by the following formula:

1) If , then the equation has a single root.

i.e., roots are equal:

2) If , then the equation has two different real roots.

i.e., and

3) If , then the equation has no real roots.

Write a C++ program that asks the user to enter a, b, and c; and outputs the roots and their types. Note that the coefficient a should not be zero.

#include <iostream>

#include <cmath>

using namespace std;

int main()

{

double a,b,c,delta, x1,x2;

cout<"Calculate the roots of a quadratic equation ax2+bx+c=0\n";

cout<"please enter a,b and c:";

cin>a>b>c;

if(a = = 0)

{

cout<"The coefficient a has to be nonzero!!!"<endl;

return 0;

}

delta=b*b-4*a*c;

if(delta= =0)

{

x1=(-b)/(2*a);

x2=(-b)/(2*a);

cout<"The equation has a SINGLE ROOT, which is: x1=x2="<x1<endl;

}

else if(delta>0)

{

x1=(-b+sqrt(delta))/(2*a);

x2=(-b-sqrt(delta))/(2*a);

cout<"The equation has TWO DIFFERENT REAL ROOTS, which are x1="<x1<" and x2="<x2<endl;

}

else

cout<"The equation has NO REAL ROOTS"<endl;

return 0;

}

QUESTION 2 (25 points)

Correct the errors in the following C++ code.

#include <iostream>

using namespace std;

int main()

{

double gpa;

cout<"Enter your gpa:";

cin>gpa;

if(gpa<0 OR gpa>4)

{

cout<"Your GPA have to be between 0 and 4.00!!!"<endl;

return 0;

}

if(gpa>=2.00);

{

if(gpa>=3.00)

{

if(gpa3.50)

cout<"You are in the high honor list! "<endl;

else

cout<"You are in the honor list!"<endl;

}

else

cout<"You have passed!"<endl;

}

else

cout<’Your GPA is below the requirements. See your advisor!’<endl;

return 0;

}

QUESTION 3 (25 points)

Write down the output of the following program for the cases in which the input is:

a) 1b) 5c) 11

#include <iostream>

using namespace std;

int main()

{

int choice;

cout<"MENU\n"

<"Enter 1 if your grade is between 0 and 50\n"

<"Enter 2 if your grade is between 50 and 60\n"

<"Enter 3 if your grade is between 60 and 70\n"

<"Enter 4 if your grade is between 70 and 80\n"

<"Enter 5 if your grade is 80 or more\n"

<"Please enter your choice from the above:";

cin>choice;

switch(choice)

{

case 1:

cout<"Your letter grade is F"<endl;

case 2:

cout<"Your letter grade is D"<endl;

break;

case 3:

cout<"Your letter grade is C"<endl;

break;

case 4:

cout<"Your letter "<endl;

cout<" grade is\n";

cout"B"<endl;

break;

case 5:

cout<"Your "<endl;

cout<"letter grade\n";

cout<" is A"<endl;

break;

default:

cout<"You have to enter 1, 2, 3, 4 or 5!!!"<endl;

return 0;

}

return 0;

}

a)

b)

c)

1