JRich29
JRich29

Reputation: 13

C++ Array and if loop. If loop ignoring values and giving wrong lines when value is input

My code:

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
double Num1, Num2, Num3, Num4, Num5, Num6, Num7, Num8, Num9, Num10, Num11, Num12;
int StudentID;


 Num1= 97 * 0.3;
 Num2= 79 * 0.3;
 Num3= 86 * 0.4;
 Num4= 91 * 0.3;
 Num5= 78 * 0.3;
 Num6= 79 * 0.4;
 Num7= 73 * 0.3;
 Num8= 77 * 0.3;
 Num9= 82 * 0.4;
 Num10= Num1 + Num2 + Num3;
 Num11= Num4 + Num5 + Num6;
 Num12= Num7 + Num8 + Num9;

 cout << "Please enter a Student ID "<< endl;
 cin >> StudentID;
 {
 if (StudentID= 2046)
    cout << "The grade for student " << StudentID << " is: " << Num10 << endl;


else if (StudentID= 7634)
    cout << "The grade for student " << StudentID << " is: " << Num11 << endl;


else if (StudentID= 8120)
    cout << "The grade for student " << StudentID << " is: " << Num12 << endl;

else if (StudentID != 2046, 7634, 8120)
    cout << "I'm sorry that is not a valid StudentID " << endl;
}



return 0;
}

Needed output (when 2046 is input): Student id: 2046 Grade for student is 87.2

Output received: Student id: 2046 Grade for student is 87.2 I'm sorry that is not a valid id

What might the issue here be? Sorry if it's obvious I'm kind of a novice coder.

Upvotes: 0

Views: 90

Answers (1)

Ron
Ron

Reputation: 15521

This condition:

if (StudentID = 2046)

always evaluates to true because the expression of StudentID = 2046 uses an assignment operator and (the entire expression) is always implicitly converted to true. It does not check if StudentID is equal to 2046. For that you need to use the equal to operator that is ==:

if (StudentID == 2046)

This condition:

if (StudentID != 2046, 7634, 8120)

is a comma separated expression that evaluates to the right-most value which is 8120 which is implicitly convertible to true. It does not check if the StudentID is not equal to all the listed numbers. To do that you would need to store the values inside a std::vector, std::array or similar and check if it matches any of them.

Upvotes: 2

Related Questions