rounding vs int output

I am writing a logic code an its works fine except for a minor problem. The code prompts the user to enter a number between 0-100, and puts it in a grade range. Anything below 0 and above 100 gives invalid entry. It does, except if you enter "100.1". It works fine for 101 and -1, so i am a little confused. I think I need to be adding int somewhere so it only does whole numbers but I don't know where. I think it might need to go in my if statement:

if (score >= 60 && score <= 69)

Is that a good guess? or should I put it somewhere else.

I have this as my first line:

int score;

I thought that would take care of it initially, but I guess not. Let me know if the question is unclear, needs more code to be helpful, etc. thanks in advance!

I am using win 7 notepad to edit and VC++ 2010 express to compile.
What is the actual issue? That 100.1 rounds down to 100? That is normal behavior, because when you enter 100.1 it gets treated as a float, then when you assign it to a variable of the type int it implicitly casts the value of 100.1 to an integer, which ALWAYS rounds down. You would need to check the input as a float if you wanted to stop 100.1 as being a valid entry, then cast it to type int.

If I misunderstood your issue, please explain a little more, and feel free to post the code (using code tags, please)
Last edited on
Here is the code:

#include <iostream>
using namespace std;

int main ()
{

int score; // Isn't this what I should do when when you say "cast it to type int"?

cout << "What is your score [0-100]? ";

cin >> score;

cin.ignore (1000, 10);

if (score >= 90 && score <= 100)

cout << "Your grade is A " << endl;

if (score >= 80 && score <= 89)

cout << "Your grade is B " << endl;

if (score >= 70 && score <= 79)

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

if (score >= 60 && score <= 69)

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

if (score >= 0 && score <= 59)

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

if (score > 100) // 100.1 needs to be an invalid entry like you said

cout << "Invalid Entry " << endl;

if (score < 0) // .001 needs to be an invalid as well

cout << "Invalid Entry " << endl;

return 0;
}

@intrexa: I think you know what I mean, and I added some comments so hopefully it will be more clear :)

thanks!
1
2
3
4
5
6
int score;
std::cin >> score; //That implicitly casts everything you put in to a type int. That means that when you 
//put a float in, like 100.1, it automatically gets converted to type int at this point (because score is an 
//int). At this point, the value stored in score is already been rounded down to 100, so anything later in
//the code can't possibly catch it. You would need to take in a type float first, check to see if it's valid,
//then cast it to int. 
thanks intrexa. I will submit it to my instructor, see if its a problem, then use your advice if it is.
Topic archived. No new replies allowed.