c - 我怎样才能让这段代码重复主要功能

标签 c loops repeat

当“你想退出吗”问题/主函数被问到并用“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/

相关文章:

c - 如何创建动态大小的结构数组?

bash 选择循环不等待输入

java - 在嵌套的 for 循环中,打印字符串 "."并在满足条件时将其替换为其他字符。 MOOC Java 周 10 'Dungeon'

html - IE6 div 中的最后三个字符在页面的其他地方重复出现?真奇怪

java - java中如何返回特定代码行

python - 使用 Python 查找文件列表中的重复次数

c - 我的代码中的声明错误

C - sigqueue 调用时 Valgrind 报告 "Syscall param points to uninitialised byte"

c - 在地址中存储数据并更改 C 中变量的地址?

php - 如何在 PHP 中按日期(今天、昨天、8 月 29 日、28 日等)对 SQL 中的 foreach 项目进行排序?