简体   繁体   中英

C++ doesn't show numbers with big decimals

I wrote a program of which the result made me wonder.
I have a double number with 3 decimals, but I need to change it to 2 decimals.
First I multiplied it with 100, then I changed it to an int , then I divided it by 100, but I don't know why the result is wrong

input: 9.857
output is: 9.8499999999999996

Here is my code:

#include <iostream>
#include <cstdio>
using namespace std;
int main(){
    double sum = 9.857, temp = 0;
    temp = int(sum * 100);
    temp = int(temp);
    sum = temp / 100;
    printf("%.16f\n", sum);
}

input: 9.857
output is: 9.850000000000000

Second code:

#include <iostream>
#include <cstdio>
using namespace std;
int main(){
    double sum = 9.857, temp = 0;
    temp = int(sum * 100);
    temp = int(temp);
    sum = temp / 100;
    printf("%.15f\n", sum);
}

Why are the answers of these two code snippets different?

In addition to floating point arithmetic, you are also using the unsafe printf-family of functions despite including <iostream> . The proper way to limit the precision of your output value in C++ is to set the ostream's precision value:

Example

#include <iostream>

int main()
{
    double sum = 9.857, temp = 0;
    std::cout.precision(4);
    std::cout << "Value = " << sum << std::endl;
    std::cout.precision(3);
    std::cout << "Value = " << sum << std::endl;
    std::cout.precision(2);
    std::cout << "Value = " << sum << std::endl;
    return 0;
}

If you wanted to do it in C, it would look like this:

Example

#include <stdio.h>

int main()
{
    double sum = 9.857, temp = 0;
    printf("Value = %.3f\n", sum);
    printf("Value = %.2f\n", sum);
    return 0;
}

If you are looking for exact values, floating point types are not the right type to use due to how they are stored (they will not be exact). This means that attempting to show 15-digits beyond the decimal is not likely to give you the same result as your input for many cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM