Possible Duplicate:
Why can't I return a double from two ints being divided可能重复:为什么我不能从被分割的两个ints返回一个double
My C++ program is truncating the output of my integer devision even when I try and place the output into a float. How can I prevent this whilst keeping those to variables (a & b) as integers?
我的c++程序正在截断我的整数devision的输出,即使我尝试将输出放入一个浮点数。如何在保持变量(a和b)为整数的同时避免这种情况?
user@box:~/c/precision$ cat precision.cpp
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a = 10, b = 3;
float ans = (a/b);
cout<<fixed<<setprecision(3);
cout << (a/b) << endl;
cout << ans << endl;
return 0;
}
user@box:~/c/precision$ g++ -o precision precision.cpp
user@box:~/c/precision$ ./precision
3
3.000
1 个解决方案
#1
64
Cast the operands to floats:
将操作数转换为浮点数:
float ans = (float)a / (float)b;
#1
64
Cast the operands to floats:
将操作数转换为浮点数:
float ans = (float)a / (float)b;