C++ 我正试图在屏幕上打印一个值

C++ 我正试图在屏幕上打印一个值,c++,cout,C++,Cout,我试图在屏幕上打印浮点值。在将两个整数值都更改为浮点值之后,输出还生成了一个浮点值。我觉得自己像个麻木的脑袋。哇,谢谢你的帮助 const float PI = 3.14159; //to hold PI value float value = 0.0; //to hold the actual value float num = 0.0; //to hold the value entered by user cout << "Please enter the number: ";

我试图在屏幕上打印浮点值。在将两个整数值都更改为浮点值之后,输出还生成了一个浮点值。我觉得自己像个麻木的脑袋。哇,谢谢你的帮助

const float PI = 3.14159; //to hold PI value
float value = 0.0; //to hold the actual value
float num = 0.0; //to hold the value entered by user
cout << "Please enter the number: "; //prompt user to enter value
cin >> num;
value = num * PI; //to hold the floating-point value
cout << "The value is " << value << "." << endl; //display result
变量值必须是浮点类型。因此,不是int值=0;试一试

原因是,在C和C++中,变量名类似于值表示内存区域。值的类型(如int)告诉编译器如何解释存储在该区域中的数据。当您定义int值时,您是在告诉编译器

在堆栈上保留足够的存储以表示整数和 稍后,解释存储为表示整数的数据。 这不是您想要的效果。

这两个变量:

int value = 0; //to hold the actual value
int num = 0; //to hold the value entered by user
是int类型。因此,它们只能保存某个大小的整数,例如32位

此外,当您这样做时:

value = num * PI; //to hold the floating-point value
乘法本身将作为浮点进行,因为PI是一个浮点。但是,您要求将结果存储在value中,value是一个整数,因此同样会得到一个截断的结果

有关更多信息,请参阅,并且。

值是一个int-为什么不希望它这样打印?
int value = 0; //to hold the actual value
int num = 0; //to hold the value entered by user
value = num * PI; //to hold the floating-point value