可能重复:
Why can't I return a double from two ints being divided
即使我尝试将输出放入浮点数,我的C ++程序也会截断整数分割的输出。如何在保持变量(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
答案 0 :(得分:77)
将操作数转换为浮点数:
float ans = (float)a / (float)b;