声明不起作用

时间:2011-08-15 09:52:10

标签: objective-c xcode while-loop

我想制作一个可以制作阶乘的程序:

int main (int argc, const char * argv[])
{   
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    //insert code here
    int numberm1;
    numberm1 > 1;

    int number, right_digit, factorial;
    NSLog(@"Ill Make Your Number A Factorial");
    NSLog(@"Enter A Number");
    scanf("%i", &number);      

    while (numberm1 > 1) {
        numberm1 = number;
        numberm1 -= 1;
        factorial = number *= numberm1;
    }

    NSLog(@"%i", factorial);
    [pool drain];
    return 0;
}

当我输入一个大于0或1的数字时,控制台上打印的数字为0.这是为什么?我的目标是模拟一个因子,例如如果我输入5,它应该是5!所以它应该是5 * 4 * 3 * 2 * 1,这是120但它打印0,请帮助。

3 个答案:

答案 0 :(得分:2)

这里有很多错误。我写了一些评论来解释:

int numberm1; // Variable not initialized, so it has an undefined value
numberm1 > 1; // This merely calculates a boolean value which is discarded

int number, right_digit, factorial; // All of these are undefined
                                    // right_digit is unused
NSLog(@"Ill Make Your Number A Factorial");
NSLog(@"Enter A Number");
scanf("%i", &number); // number now maybe contains the value given by the user
                      // except you should use %d instead of %i, so I think the behavior here is still undefined
                      // Also, the value of numberm1 is still undefined
while (numberm1 > 1) { // If the compiler initializes all variables to 0,
                       // then this loop never runs.
    numberm1 = number; 
    numberm1 -= 1; // Why not say numberm1 = number - 1; ?
    factorial = number *= numberm1; // number is now number * numberm1, which
                                    // means if number was > 2, then on the next 
                                    // step of the loop, numberm1 will now be even 
                                    // larger, leading to a loop that only ends after
                                    // number overflows into the negatives...
}

相反,你想要做的是:

int number;
int factorial = 1;

NSLog(@"I\'ll make your number a factorial");
NSLog(@"Enter a number");
scanf("%d", &number);

while (number > 1) {
    factorial *= number--; // This makes factorial equal factorial * number
                           // Then it decrements the value of number by 1
}

但即便如此,因子也会迅速溢出。

答案 1 :(得分:0)

您的numberm1将始终小于1,因为它实例化为0并且您永远不会在while循环之前分配它。因此while循环永远不会运行。尝试将numberM1实例化为大于1的正数,即第6行

numberm1 > 1;

应该成为

numberm1 = 10;

答案 2 :(得分:0)

int numberm1; numberm1 > 1;完全错误。将其更改为:

int numberm1;
numberm1 = 50;