Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

c - Why the infinite loop when data type is unsigned int?

The below code runs perfectly.Gives the correct output but, the moment I change the sign of the variables from signed to unsigned the program runs into an infinite loop. The program is to find the factorial of integers. The value of any variable doesn't get negative anywhere I am aware of the modular behavior of the unsigned int.

#include<stdio.h>

int main(void)
{
    int a[200], i,index, number, next, count, temp, test, x;

    scanf(" %d", &test);

    while(test--)
    {
        scanf(" %d", &number);
        a[0]=1;
        count=1;    //1 digit
        for(next=2;next<=number;++next)
        {
            index=0;temp=0;
            for(i=0;i<count;++i)
            {
                x=a[index]*next+temp;
                a[index]=x%10;
                temp=x/10;
                ++index;
            }
            while(temp!=0)
            {
                a[count++]=temp%10;
                temp=temp/10;
            }
        }
        for(i=count-1;i>=0;--i)
        printf("%d",a[i]);
        printf("
");
    }
    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is that,

for(i=count-1;i>=0;--i)

Will never exit if i is unsigned. Because i is unsigned it will always be greater than or equal to zero, and thus the loop can't end.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...