无法让 cout 显示小数 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17091517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can't get cout to display decimals c++
提问by user1677657
i can't get coutto display decimals (using eclipse c++ and mingw)
我无法cout显示小数(使用 eclipse c++ 和 mingw)
#include <iostream>
using namespace std;
int main() {
int a = 55, b = 60, c = 70;
double avgResult;
avgResult = ((a + b + c) / 3);
cout << avgResult; //should display 61.666666
return 0;
}
my output is 61 when I would expect it to be 61.666666.
当我期望它是 61.666666 时,我的输出是 61。
I can get it to display the decimals using
我可以使用它来显示小数
cout << std::fixed << std::setprecision(2) << avrResult;
cout << std::fixed << std::setprecision(2) << avrResult;
but I thought I didn't need to do that unless I wanted a specific decimal precision.
但我认为除非我想要特定的小数精度,否则我不需要这样做。
If I do something like
如果我做类似的事情
double value = 12.345;
cout << value;
it displays correctly so it leads me to believe that the above problem has to do with the use of intvalues in my calculation of double avgResult
它显示正确,因此让我相信上述问题与int我在计算中使用的值有关double avgResult
btw I am new to c++ and am just starting to learn
顺便说一句,我是 C++ 新手,刚刚开始学习
回答by Andrew
((a + b + c) / 3)- that has an inttype. Change it to ((a + b + c) / 3.0)to get double
((a + b + c) / 3)- 有一个int类型。将其更改((a + b + c) / 3.0)为double
回答by Sorin
You compute (a + b + c) / 3 and then you store it in avgResult. avgResult is a double, but a + b + c is int, 3 is int, so the result of division is int. So you finally store an int in your double variable.
您计算 (a + b + c) / 3,然后将其存储在 avgResult 中。avgResult是double,但是a+b+c是int,3是int,所以除法的结果是int。所以你最终在你的 double 变量中存储了一个 int 。
Another way to get a double result, besides the already mentioned one:
除了已经提到的方法之外,另一种获得双重结果的方法:
avgResult = a + b + c;
avgResult /= 3;

