当“你想退出吗”问题/主函数被问到并用“n”回答时,我需要代码一次又一次地询问问题,直到用户完成程序。又名根据需要重复
int getNumTerms()
{
int n;
printf("Enter the number of terms: \n");
scanf("%d",&n);
return n;
}
double coshyper (double x, int n)
{
int i;
double sum=1, term=1;
for (i=1; i<n; i++)
{
term=(x*x/(2.0*(double)i*(2.0*(double)i-1.0)))*term;
sum=sum+term;
}
return sum;
}
int main()
{
char q;
printf("Do you wish to quit(y/n)?\n");
scanf("%c",&q);
if(q=='y')
{
printf("Program Terminated\n");
}
while(q=='n')
{
int n;
double x;
printf("Enter x: \n");
scanf("%lf",&x);
n=getNumTerms();
double result = coshyper(x,n);
printf("The value for cosh(%.3lf) for %d terms is %.6lf\n",x,n,result);
}
}
最佳答案
您可以将 main 更改为如下所示:
int main()
{
char q = 'n';
do{
if(q == 'y'){
printf("Program Terminated\n");
break;
}
if(q == 'n'){
int n;
double x;
printf("Enter x: \n");
scanf("%lf",&x);
n=getNumTerms();
double result = coshyper(x,n);
printf("The value for cosh(%.3lf) for %d terms is %.6lf\n",x,n,result);
}
else
{
printf("Invalid");
}
printf("Do you wish to quit(y/n)?\n");
scanf("%c",&q);
}while(1);
return 0;
}
关于c - 我怎样才能让这段代码重复主要功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52685517/