why is this double type number getting rounded?

I have the following very simple code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <string>
#include <Windows.h>

void Problem2();

int main()
{
	Problem2();
	return 0;
}


void Problem2()
{
	using namespace std;
	double score;
	char grade, flag = 'n';
	do {
		if (flag == 'y') {
			cout << "Invalid score. Score must be between 0 and 100" <<"\n";
			Sleep(1500);
		}
		cout << "Enter a score: ";
		cin >> score;
		flag = 'y';
	} while (score < 0 || score >100);
	if (90 <= score && score <= 100)
		grade = 'A';
	else if (80 <= score && score < 90)
		grade = 'B';
	else if (70 <= score && score < 80)
		grade = 'C';
	else
		grade = 'F';
	cout << "Your grade is " << grade << "\n";
}



this code checks the score and categorize them into grades;

According to the code, the score of x=89.99999999999999999999

(20 9's after decimal dot)

must award grade of B, but when I run it it actually awards A. What I suspect is that x is rounded to nearest number 90, but why does this happen? As far as I'm aware, doesn't double data type can store data up to far better accuracy?
I'm afraid double doesn't have better precision than that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>

int main()
{
	std::string inputString = "89.99999999999999999999";
	double inputValue = std::stod(inputString);
	double smallerValue = std::nextafter(inputValue, 0);
	
	std::cout << std::fixed << std::setprecision(20);
	
	std::cout << "        Your input: " << inputString << '\n';
	std::cout << "   Value as double: " << inputValue << '\n';
	std::cout << "Next smaller value: " << smallerValue << '\n';
}
        Your input: 89.99999999999999999999
   Value as double: 90.00000000000000000000
Next smaller value: 89.99999999999998578915

Last edited on
Topic archived. No new replies allowed.