带模数运算符的不需要的输出和' pow'

时间:2016-03-04 17:36:38

标签: c

以下显示的代码

#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

2 个答案:

答案 0 :(得分:1)

I suspect that the pow() is not numerically stable on that platform you're using. You will get 24, if pow(10, 2) returns a double that is little less than 100, e.g. 99.9999999998765, which when cast to (int) would be truncated, resulting in 99, and thus you get 123 % 99 == 24. You could test what is the output of

printf("%.100f\n", pow(10, 2));

If that be the case, and since it seems you're really doing integer math, I'd have another loop variable for multiples of 10:

int tens;

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

(Additionally, the initial version of the code had the following problems: the variable int temp; was read uninitialized (and #include <math.h> was missing by mistake). Thus the code had also undefined behaviour.

The C11 standard appendix J2 says that among others, the behaviour of a program is undefined, when:

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).


P.S. The while (temp >= 0) condition is needless (and that is a cause for undefined behaviour), except for a complicated way to ensure that a positive integer is entered; as you'd break out anyway at temp == 0, so you could replace it with while (1))

答案 1 :(得分:1)

I see the following errors:

while(temp>=0)

but temp is not initialized.

temp = a / pow(10,n);

but temp is integer and the calculation is double. You loose precision, which is the probable cause of your wrong output.