У меня есть такая программа:
int main(void){
int x, number, factorial;
// The objective of this program is to compute the factorial
// for a user inputted number, stopping once "-1" is entered.
printf("Please enter a positive number for factorial calculation (-1 to end) :");
scanf("%d", &number);
for (x = 1; x <= number; x++){
factorial *= x;
if (x == -1){
break;
}
}
printf("factorial for %d is %d", number, factorial);
}
Который должен выводиться следующим образом:
Please enter a positive number for factorial calculation (-1 to end) :4
factorial for 4 is 24
Please enter a positive number for factorial calculation (-1 to end) :6
factorial for 6 is 720
Please enter a positive number for factorial calculation (-1 to end) :8
factorial for 8 is 40320
Please enter number for factorial calculation (-1 to end) :-1
Но я продолжаю получать это (в двух разных прогонах):
Please enter a positive number for factorial calculation (-1 to end) :4
factorial for 4 is 24
Please enter a positive number for factorial calculation (-1 to end) :-1
factorial for -1 is 1
Как я могу сделать так, чтобы он продолжал запрашивать дополнительные числа, пока я не наберу -1? Кроме того, почему ввод здесь -1 дает мне факториал вместо остановки цикла?
2 ответа
Вы можете обернуть вычисление факториала внутри цикла следующим образом:
int number;
int factorial = 1;
while(true) {
printf("Please enter a positive number for factorial calculation (-1 to end) :");
scanf("%d", &number);
if (number == -1)
break; // or just return as you need
for (x = 1; x <= number; x++){
factorial *= x;
}
printf("factorial for %d is %d", number, factorial);
factorial = 1;
}
В этом случае вы получите число в качестве ввода и просто начнете проверять, что пользователь ввел.
В своем коде вы проверяли внутри цикла for, чтобы переменная x
отличалась от -1, но это условие никогда не выполнялось, поскольку вы присваивали 1 x
только в начале цикла. В этом случае вы должны проверить number
, но это будет не совсем правильно.
Используйте цикл While и проверьте значение после ввода пользователем, чтобы узнать, нужно ли вам выйти из цикла:
int main(void){
int x, number, factorial;
// The objective of this program is to compute the factorial
// for a user inputted number, stopping once "-1" is entered.
while (true){
printf("Please enter a positive number for factorial calculation (-1 to end) :");
scanf("%d", &number);
if (number == -1){
break;
}
for (x = 1; x <= number; x++){
factorial *= x;
}
printf("factorial for %d is %d", number, factorial);
}
}
Новые вопросы
c#
C # (произносится как «резкий») - это высокоуровневый, статически типизированный язык программирования с несколькими парадигмами, разработанный Microsoft. Код C # обычно нацелен на семейство инструментов и сред выполнения Microsoft .NET, включая, среди прочего, .NET Framework, .NET Core и Xamarin. Используйте этот тег для вопросов о коде, написанном на C # или в формальной спецификации C #.