bob*_*808 0 c loops function break
#include <stdio.h>
#include <math.h>
long factcalc(int num1);
int main(void)
{
int num1;
long factorial;
int d;
int out;
printf("Please enter a number that is greater than 0");
scanf_s("%d", &num1);
if (num1 < 0) {
printf("Error, number has to be greater than 0");
} else if (num1 == 0) {
printf("\nThe answer is 1");
} else {
factorial = factcalc(num1);
printf("\nThe factorial of your number is\t %ld", factorial);
}
return 0;
}
long factcalc(int num1)
{
int factorial = 1;
int c;
for (c = 1; c <= num1; c++)
factorial = factorial * c;
return factorial;
}
Run Code Online (Sandbox Code Playgroud)
我想知道,我怎么做到这样,程序一直要求用户输入,直到用户输入'-1'?因此,即使在计算了一个数字的阶乘之后,它仍然要求更多的数字,直到用户输入-1,同样适用于显示错误消息等的情况.提前致谢.
通过引入无限循环可以很容易地实现.
#include <stdio.h>
#include <math.h>
#ifndef _MSC_VER
#define scanf_s scanf
#endif
long factcalc(int num1);
int main(void)
{
int num1;
long factorial;
int d;
int out;
for (;;) {
printf("Please enter a number that is greater than 0");
scanf_s("%d", &num1);
if (num1 == -1) {
break;
}
else if (num1 < 0) {
printf("Error, number has to be greater than 0");
}
else if (num1 == 0) {
printf("\nThe answer is 1");
}
else {
factorial = factcalc(num1);
printf("\nThe factorial of your number is\t %ld", factorial);
}
}
return 0;
}
long factcalc(int num1) {
int factorial = 1;
int c;
for (c = 1; c <= num1; c++)
factorial = factorial * c;
return factorial;
}
Run Code Online (Sandbox Code Playgroud)