#include <stdio.h>
//#include <stdlib.h>
int main(void){
int userScore = 0; //Stores the scores that the user inputs
float meanValue = 0.0f; //Stores the user mean of all the notes
char testChar = 'f'; //Used to avoid that the code crashes
char grade = 'E'; //Stores the final
int i = 0; //Auxiliar used in the for statement
printf("\nWelcome to the program \n Tell me if Im clever enough! \n Designed for humans \n\n\n");
printf("Enter your 4 notes between 0 and 100 to calculate your course grade\n\n");
// Asks the 4 notes.
for ( ; i<=3 ; i++ ){
printf("Please, enter your score number %d: ", i+1);
//If the note is not valid, ask for it again
//This is tests if the user input is a valid integer.
if ( ( scanf("%d%c", &userScore, &testChar)!=2 || testChar!='\n')){
i-=1;
scanf("%*[^\n]%*c");
}else{ //Enter here if the user input is an integer
if ( userScore>=0 && userScore<=100 ){
//Add the value to the mean
meanValue += userScore;
}else{ //Enter here if the user input a non valid integer
i-=1;
//scanf("%*[^\n]%*c");
}
}
}
//Calculates the mean value of the 4 scores
meanValue = meanValue/4;
// Select your final grade according to the final mean
if (meanValue>= 90 && meanValue <=100){
grade = 'A';
} elseif(meanValue>= 80 && meanValue <90){
grade = 'B';
} elseif (meanValue>= 70 && meanValue <80){
grade = 'C';
} elseif(meanValue>= 60 && meanValue <70){
grade = 'D';
}
printf("Your final score is: %2.2f --> %c \n\n" , meanValue, grade);
return 0;
}
the thing is here ( scanf("%d%c", &userScore, &testChar)!=2 || testChar!='\n'))I don't understand about how scanf &testchar work because when I delete it the first output stuck at the loop and there also || testChar!='\n'what is this for ? also can anyone tell me what the use of !=2 ?
and the more interesting thing is how the code can be execute if...else statement at the same time without needing any true or false? it start from if after first statement work then move on to the else which is have the second statement.(I always thought if won't ever move to else unless it statement is false but because it not a typical boolean expression I having hard time understand it)
also is scanf("%*[^\n]%*c" save the previous scanf(after userscore and testchar)
honestly I never use that kind of scanf before.
ignoring scanf, c++ is true if not zero, and false for zero. Boolean expressions return 1 or 0.
so if value > 90 == true
is the same as
if value > 90
so most people leave the == true off as it is just visual clutter.
the logic is terrible.
you should chain the logic so you only have to do the least amount of work.
here, try
grade = 'F';
if( mean >= 90) grade = 'A'; else
if(mean >= 80) grade = 'B'; else
… etc
you don't need to check if its >80 and < 90. If it failed the first test, >= 90, then you KNOW its < 90. Don't need to check it a second time.
and, you can do this with a lookup table without all the tests. This is really the better way for this specific code.