#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define pi 3.14159265
int main()
{
int n;
int fact=1;
int i;
char repeat;
do{
//part a
printf("Please input a positive whole number value to be stored as 'n': ");
scanf("%d",&n);
while(n<0){
printf("Improper value of n. Please input a positive whole number value to be stored as 'n': ");
scanf("%d",&n);
}
//part b
if (n>0){
printf("n is now %dn",n);
for(i=1;i<=n;i++){
fact=fact*i;
}
//printf("The factorial of %d is %d.n",n,fact);
}
else{
printf("The factorial of 0 is 1.n");
}
//part c
double approx = (pow((double)n,n)*exp(-n))*sqrt(((2*n)+(1/3))*pi);
//printf("Approx is %lf",approx);
//part d
printf("%d! equals approximately %lf.n",n,approx);
printf("%d! is %d accurately.n",n,fact);
//part e
double perror=((fact-approx)/(fact))*100;
printf("The approximate value is off by %lf%%n",perror);
//part f
printf("Would you like to restart with another value? Respond y or n: ");
scanf("%c",&repeat);
} while(repeat=='y');
/*I was going to have the program restart if the user input "y" at the end of the program but I can't
figure out why it isn't working.*/
return 0;
}
我对C编程还很陌生,还在学习基础知识,所以任何解释都很感激。我唯一没有弄明白的部分是为什么……While循环在代码的开头和结尾不工作。
scanf("%c",&repeat);
在%c
之前需要一个空格,以便使用之前调用scanf
留下的换行符:
scanf(" %c",&repeat);
从https://linux.die.net/man/3/scanf:
转换
c
匹配长度由属性指定的字符序列最大字段宽度(默认为1);下一个指针必须是指向字符,并且必须有足够的空间容纳所有字符(不添加终止null字节)。通常的前导空白的跳过是抑制。若要先跳过空白,请在.
另外,永远不要相信用户,总是在使用scanf
之前初始化变量,否则如果失败,你可能会最终读取未初始化的值(垃圾):
char repeat;
应该
char repeat = 'n';
或者至少检查scanf
的结果,用合适的默认值填充变量:
char repeat;
...
if (scanf(" %c",&repeat) != 1)
{
repeat = 'n';
}