C++ 将两个整数相除以产生浮点结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12447325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:16:38  来源:igfitidea点击:

Dividing two integers to produce a float result

c++precisioninteger-division

提问by jwbensley

Possible Duplicate:
Why can't I return a double from two ints being divided

可能的重复:
为什么我不能从被分割的两个整数中返回一个双精度值

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++ 程序也会截断整数部分的输出。如何在将变量(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

回答by cdiggins

Cast the operands to floats:

将操作数转换为浮点数:

float ans = (float)a / (float)b;