gpt4 book ai didi

c - 带有模运算符和 ' pow ' 的不需要的输出

转载 作者:太空宇宙 更新时间:2023-11-04 08:15:56 26 4
gpt4 key购买 nike

对于下面显示的代码

#include<stdio.h>
#include<math.h>
int main()
{
int a,i,n=0;
int temp=0;
scanf("%d",&a);
//for number of digits
while(temp>=0)
{
n++;
temp = a / pow(10,n);
if(temp==0)
break;
}
printf("%d\n",n);
for (i=1;i<=n;i++)
{
temp = a % (int)pow(10,i);
printf("%d\n",temp);
}
return 0;
}

输出为(输入为123)

123
3
3
24
123

Image of the output given by gcc

所以问题是为什么 24 而不是 23?

请检查图像,因为在线编译器(ideone)给出的输出是23。只有gcc的输出有24

最佳答案

我怀疑 pow()在您使用的平台上数值不稳定。你会得到 24 , 如果 pow(10, 2)返回 double小于 100 的一点,例如99.9999999998765,当转换为 (int) 时将被截断,导致 99 ,因此你得到 123 % 99 == 24 .您可以测试

的输出是什么
printf("%.100f\n", pow(10, 2));

如果是这样的话,并且因为看起来你真的在做整数数学,我会有另一个循环变量来表示 10 的倍数:

int tens;

for (i = 1, tens = 10; i < n; i++, tens *= 10) {
temp = a % tens;
printf(tens);
}

(此外,代码的初始版本存在以下问题:变量 int temp; 被读取为未初始化(并且错误地丢失了 #include <math.h>)。因此代码也具有未定义的行为。

C11 标准附录 J2 指出,在以下情况下,程序的行为是未定义的:

An lvalue designating an object of automatic storage duration that could have been declared with the register storage class is used in a context that requires the value of the designated object, but the object is uninitialized. (6.3.2.1).


附言while (temp >= 0)条件是不必要的(这是未定义行为的原因),除了确保输入正整数的复杂方法外;因为无论如何你都会在temp == 0爆发,因此您可以将其替换为 while (1) )

关于c - 带有模运算符和 ' pow ' 的不需要的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35802524/

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