I am completing an assignment for a class where the prompt states Fractional scores, such as 8.3 are not allowed another requirement was to not allow scores < 0 or scores >10
I think I was able to successfully make it so the program does not allow scores < 0 or scores >10 but I do not know how to not accept a fractional score
If the user enters a decimal I would like to display a message saying "only whole numbers are accepted" and prompt the user to enter the number again correctly
1 2 3 4 5 6 7 8 9 10 11 12
int getJudgeData(string judge)
{
int input = -1;
while ( input < 0 || input > 10 )
{
cout << "Enter the score from " << judge <<endl;
cin >> input;
}
return input;
}
Here is another way, but make sure to #include <cmath>
the ceil() function rounds the number up.
The only way it won't round up is if it is whatever.0 (already rounded!)
So you make it round up all decimals.
If the user entered number does not equal the rounded up number, it must not be whole.
;)
1 2 3 4 5 6 7
double input = -1.0;
while (input < 0.0 || input > 10.0 || ceil(input) != input)
{
cout << "Enter the score from 1-10" << endl;
cin >> (double)input;
}
in order to check if they entered a non-whole number, you need to have a data type which can receive it. if you make input a double, then you can check with : while( input < 0 || input > 10 || (input - (int)input) > 0 ) to see if they entered a floating point value.
There are three things going on here, get a number, make sure it is an integer, and make sure it is in range. Therefore, you want to make three functions:
#include <iostream>
double getNumber(void);
int getInteger(void);
int getIntegerInRange(constint low, constint high);
int main(void)
{
constint low = 0;
constint high = 10;
std::cout << "Please enter an integer in range " << low << " and " << high << ": ";
int number = getIntegerInRange(low, high);
std::cout << "You entered: " << number << '\n';
std::cin.get(); // because I'm using Visual Studio
return 0;
}
double getNumber(void)
{
double number;
while (!(std::cin >> number)) // the user entered a letter
{
std::cin.clear(); // clear cin's error state
std::cin.ignore(80, '\n'); // ignore whatever the user typed
std::cout << "Only numbers are accepted, try again: ";
}
std::cin.ignore(80, '\n'); // remeber to clear the input buffer
return number;
}
int getInteger(void)
{
double number = getNumber();
while (number != static_cast< int >(number)) // casting to int changes the number
{
std::cout << "Only integers are accepted, try again: ";
number = getNumber();
}
returnstatic_cast< int >(number); // return number casted to int
}
int getIntegerInRange(constint low, constint high)
{
int number = getInteger();
while (number < low || number > high)
{
std::cout << "Number must be in range ( " << low << ", " << high << " ), try again: ";
number = getInteger();
}
return number;
}