C ++中llround()和round()函数有什么区别?

问题描述 投票:0回答:1

所以我有这个问题的原因是,我在做一个必须舍弃最终答案的问题。现在,

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代码块也不应该起作用。那我想念什么呢?

谢谢!

c++ rounding built-in
1个回答
0
投票

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
© www.soinside.com 2019 - 2024. All rights reserved.