【问题标题】:What's the difference between llround() and round() function in C++?C++ 中的 llround() 和 round() 函数有什么区别?
【发布时间】:2020-04-20 07:07:28
【问题描述】:

所以我有这个问题的原因是我正在做一个我们必须对最终答案进行四舍五入的问题。现在,

cout << round(answer); //this didn't pass one test case
//the following block of code passed all test cases
if (answer-(int)answer>0.5) cout << int(answer)+1; 
else cout << (int)answer;
cout << llround(answer); //this passed all test cases

那么,round()llround() 对于这种行为有什么区别?如果answer 变量太大以至于不适合int 类型,那么if-else 代码块也不应该工作。那么我错过了什么?

谢谢!

【问题讨论】:

  • round 返回浮点值,而lround 返回longllround 返回long long
  • 您的 if-else 实际上是不正确的。 roundllround 都从零开始舍入中途的情况。将&gt; 更改为&gt;=
  • 请不要修复您的问题中与您的问题相关的问题。您问为什么会有差异,&gt; 而不是 &gt;= 是造成差异的原因之一。不要在问题中解决这个问题。我回滚了编辑
  • @idclev463035818 我可以知道人们对 SO 的问题投反对票的原因吗?这是我的一个真正的问题,所以是我最后的选择。我问过我的同龄人,但他们没有回答这个问题。此外,我也尝试查看其他帖子。
  • 不包括minimal reproducible example,实际和预期的输出应该是这个问题难以正确回答的另一个原因

标签: c++ rounding built-in


【解决方案1】:

round() 返回一个浮点值,而您的选择返回整数值。使用cout的默认格式,输出应该没有区别,但如果你改变了格式,可能会有区别:

double answer = 1.5;
cout << round(answer) << " " << llround(answer) << "\n"; // Prints 2 2
cout << std::fixed << setprecision(5);
cout << round(answer) << " " << llround(answer) << "\n"; // Prints 2.00000 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 2016-03-26
    • 2013-09-29
    • 2016-02-17
    相关资源
    最近更新 更多