Пока заявление не работает - PullRequest
0 голосов
/ 15 августа 2011

Я хочу создать программу, в которой я могу сделать факториал:

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, когда я набираю число больше 0 или 1. Почему это?Моя цель - смоделировать факториал, например, если я наберу 5, это должно быть 5!так что это должно быть 5 * 4 * 3 * 2 * 1, что равно 120, но выводит 0, пожалуйста, помогите.

Ответы [ 3 ]

2 голосов
/ 15 августа 2011

Здесь много чего не так. Я написал комментарии, чтобы объяснить:

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
}

Но даже в этом случае факториал очень быстро переполнится.

0 голосов
/ 15 августа 2011

Это int numberm1; numberm1 > 1; совершенно неправильно.Измените его на:

int numberm1;
numberm1 = 50;
0 голосов
/ 15 августа 2011

Ваш номерm1 всегда будет меньше 1, так как он соответствует 0, и вы никогда не присваиваете ему до цикла while.Поэтому цикл while никогда не запускается.Попробуйте создать экземпляр numberM1 для положительного числа, большего 1, т.е. в строке 6

numberm1 > 1;

должно стать

numberm1 = 10;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...