我正在尝试将浮点值打印到屏幕上。在将两个整数值都更改为浮点值之后,输出也产生了一个浮点。我感觉像个麻木的头骨。哇,谢谢你的帮助!
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
答案 0 :(得分:1)
这两个变量:
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
乘法本身将以float
进行,因为PI
是float
。但是,您要求将结果存储在value
中,它是一个整数,因此再次会得到截断的结果。
有关更多信息,请参见conversion rules和implicit conversions。
答案 1 :(得分:0)
变量value
必须为浮点类型。因此,请尝试使用{p>而不是int value = 0;
float value = 0.0;
或
double value = 0.0;
原因是,在C和C ++中,像value
这样的变量名表示内存区域。值的类型(例如int
)告诉编译器如何解释存储在该区域中的数据。定义int value
时,您是在告诉编译器
这不是您想要的效果。