gpt4 book ai didi

c - 为什么我在 1/2 这样的浮点表达式中得到零?

转载 作者:行者123 更新时间:2023-11-30 21:33:38 24 4
gpt4 key购买 nike

请有人解释一下这种行为:

#include <stdio.h>

int main(int argc, char **argv){

printf("%f", ( 1 / 2 ) );
return 0;

}

/* output : 0.00000 */

最佳答案

正是 quantdev 所说的。编写 C 语言的人的想法是这样的:“嘿,让我们将任意两个整数的被除数设为整数,因为整数非常有用,而且当你尝试索引一个整数时,使用 float 可能会扰乱你的风格。”大批”。因此,C 编译器继续将余数扔进垃圾箱,只剩下 0。

1/2

要声明你想要你的该死的 double (或 float ),你最好将除法中的两个数字之一设为 float !因此,

1/2.0

并且,在上下文中......

不是你想要的:

printf("%f", ( 1/2 ) ); ,

你想要什么:

printf("%f", ( 1/2.0 ) ); ,

关于c - 为什么我在 1/2 这样的浮点表达式中得到零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31084800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com