C code至圆数字 [英] C code to round numbers
本文介绍了C code至圆数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么办法圆数字用C?
Is there any way to round numbers in C?
我不希望使用CEIL和地板。是否有任何其他的选择吗?
I do not want to use ceil and floor. Is there any other alternative?
我碰到这个code片段来了,当我Google的答案:
I came across this code snippet when I Googled for the answer:
(int)(num < 0 ? (num - 0.5) : (num + 0.5))
上面一行总是打印值4,即使浮动NUM = 4.9。
The above line always prints the value as 4 even when float num =4.9.
请提出一个解决方案。
推荐答案
4.9 + 0.5是5.4,这不可能轮4,除非你的编译器被严重损坏。
4.9 + 0.5 is 5.4, which cannot possibly round to 4 unless your compiler is seriously broken.
我刚刚确认了一派code给出了正确答案为4.9。
I just confirmed that the Googled code gives the correct answer for 4.9.
marcelo@macbookpro-1:~$ cat round.c
#include <stdio.h>
int main() {
float num = 4.9;
int n = (int)(num < 0 ? (num - 0.5) : (num + 0.5));
printf("%d\n", n);
}
marcelo@macbookpro-1:~$ make round && ./round
cc round.c -o round
5
marcelo@macbookpro-1:~$
这篇关于C code至圆数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文