I\'m trying to come up with a program that calculates grades given from the users input. I am also trying to set a limit on how high or low the user input can be (i.e 0 <
There are at least four issues I noticed in your code.
Firstly, as mentioned, you should use M
suffix to tell the C# compiler that it is a decimal
for accepted comparison:
if (Exam_1 < 0.0M | Exam_1 > 100.0M)
But secondly, use ||
instead of |
, because you want to do OR
operation, not Bitwise-OR
if (Exam_1 < 0.0M || Exam_1 > 100.0M) //change | to ||
And thirdly, I think quite important for you to know this: you wouldn't need decimal
data type for exam mark (unless your exam mark can be of format 99.12345678901234556789012345 - which is quite impossible).
decimal
is normally used for numbers requiring very high precision (such as money
calculation in the bank) up to more than 16-digit accuracy. If your exam mark does not need that, don't use decimal
, it is overkill. Just use double
or int
or float
for your Exams
and you are most probably in the right track.
Fourthly, about your error handling, this is incorrect way of doing it:
if (Exam_1 < 0.0 | Exam_1 > 100.0)
Console.Write("Exam score cannot be less than 0. or greater than 100.0. Please re-enter the score for Exam 1 :");
Exam_1 = Convert.ToDecimal(Console.ReadLine());
due to two reasons:
Exam_1
is outside of the block (there isn't {}
bracket)if
while you should use while
This is the right way to do it:
double Exam_1 = -1; //I use double to simplify
Console.Write("Please enter score for Exam 1 : ");
Exam_1 = Convert.ToDouble(Console.ReadLine());
while (Exam_1 < 0.0 || Exam_1 > 100.0) { //see the curly bracket
Console.Write("Exam score cannot be less than 0. or greater than 100.0. Please re-enter the score for Exam 1 :");
Exam_1 = Convert.ToDouble(Console.ReadLine());
} //see the end curly bracket
In C# language, indentation does not mean scoping, unlike in language like Python.