除法不输出正确答案C ++ [英] Division not outputting correct answer c++
问题描述
我是C语言的新手,我正在尝试编写一个基本的数学程序来适应这种语言.当我尝试将问题9/2或任何带有小数的问题解答时,答案似乎是错误的.我想要一个"4.50"的输出,但是我继续得到"4.00".是什么原因引起的,以及如何预防.谢谢
I'm new to c++ and I'm trying to make a basic math program to get warmed up to the language.when I try to do the problem 9/2 or anything with a decimal the answer seems to be wrong. I would like an output of "4.50" but I keep on getting "4.00". What causes this and how do I prevent it. thanks
double INN = 0.0;
INN = 9 / 2;
std::cout.precision (3);
std::cout << std::showpoint << INN << endl;
推荐答案
INN = 9/2;
将 4.0
分配给 INN
.
将其替换为 INN = 9.0/2.0;
以分配 4.5
.
说明:
因为 9
和 2
都是整数,所以 9/2
总是产生整数除法,其结果也是整数.因此,结果必须四舍五入,并四舍五入到最接近的整数.
Because both 9
and 2
are integers, 9 / 2
always results in an integer division, the result of which is an integer too. Thus the result must be rounded, and is rounded down to the nearest integer.
9.0
和 2.0
是双精度的,因此 9.0/2.0
将导致浮点除法,从而导致双精度值.
Whereas 9.0
and 2.0
are doubles, thus 9.0 / 2.0
will result in a floating point division, which results in a double value.
这篇关于除法不输出正确答案C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!