开发者

While statement not working

I want to make a program where i can make factorial:

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;
}

The number that pr开发者_如何学编程ints on the console is 0 when i type in a number bigger than 0 or 1. Why is this? My objective is to simulate a factorial e.g. if i type in 5, it should be 5! so it should be 5*4*3*2*1 which is 120 but it prints 0, please help.


There's a lot wrong here. I've written comments to explain:

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

Instead, what you want to do is this:

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
}

But even then, factorial will overflow very quickly.


Your numberm1 will always be less than 1 as it instantiates to 0 and you never assign to it before your while loop. The while loop therefore never runs. Try instantiating numberM1 to a positive number greater than 1 i.e. at line 6

numberm1 > 1;

should become

numberm1 = 10;


This int numberm1; numberm1 > 1; is completely wrong. Change it to:

int numberm1;
numberm1 = 50;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜