在代码块中使用双精度给了我 int 输出

Use of double in codeblocks gives me int output

本文关键字:int 输出 双精度 代码      更新时间:2023-10-16
#include <iostream> using namespace std;
int main() 
{  
 double x=5.0,y=4.0,z;  
 z=x+y;     
 cout<<x<<endl<<y<<endl<<z;   
 return 0;
} 

上面的程序给了我以下输出:549当我将变量声明为双精度,甚至 z 为双精度时,为什么我会将输出为整数值 (9)?

cout在这里很有帮助:如果double值是整数,则默认情况下,它不显示小数分隔符,后跟任意数量的零。

如果您想显示与平台上特定double具有的精度一样多的数字,请在以下行中使用一些内容

cout.precision(std::numeric_limits<double>::max_digits10);
cout << fixed << x << endl;

点后没有数字的浮点数默认打印为整数。

要始终显示浮点数,请使用 setiosflags(ios::showpoint)

您可以将其与 fixedsetprecision(n) I/O 标志结合使用,以限制浮点后要打印的位数。例如:

double d = 5.0;
cout << setiosflags(ios::showpoint) << d << endl; // prints 5.00000
cout << setiosflags(ios::showpoint) << fixed << setprecision(1)
     << d << endl; // prints 5.0