【问题标题】:How to reset do while loop within while loop?如何在while循环中重置do while循环?
【发布时间】:2015-09-18 06:46:04
【问题描述】:
#include <stdio.h>

int main()
{

int comp,loop=1,tcomp=0;
char cont;
char name[50];
float donate=0,total,gtotal;

printf("\nGot representative? [Y to continue]: ");
scanf("%s", &cont);

while(cont=='y'){
    printf("\nRepresentative name : ");
    scanf("%s", &name);
    printf("How many companies? : ");
    scanf("%d", &comp);
    tcomp+=comp;
    do{
        printf("Enter amount of donation : ");
        scanf("%f", &donate); loop++;
        total+=donate;}
        while(loop<=comp);
    printf("%s : %.2f\n", name, total);

    printf("\nGot representative? [Y to continue]: ");
    scanf("%s", &cont);}


    printf("\nTotal Representative : %d", tcomp);
    gtotal+=total;
    printf("\nTotal Donations : %.2f\n", gtotal);
}

当前输出:

Got representative? [Y to continue]: y

Representative name : ABC

How many companies? : 3

Enter amount of donation : 1

Enter amount of donation : 2

Enter amount of donation : 3

ABC : 6.00

Got representative? [Y to continue]: y

Representative name : ZXC

How many companies? : 3

Enter amount of donation : 1

ZXC : 7.00

正如您在此处看到的,第二个循环没有重置,而是对第一个循环的数量求和。我该如何纠正这个问题?如何使循环每次都重新开始? p/s : 有人专门要求我使用 while 并执行 while 循环。

【问题讨论】:

  • 你看过编译器发出的警告了吗?
  • 在外循环中使循环 = 0。
  • scanf("%s", &amp;cont) 应该是 scanf("%c", &amp;cont)totalgtotal 在没有被初始化的情况下使用。你用什么编译器?
  • 在本站发布代码之前请修正缩进。

标签: c loops while-loop do-while


【解决方案1】:

在您更正的代码下方。

int main()
{

    int comp,loop=1,tcomp=0;
    char cont;
    char name[50];
    float donate=0,total=0,gtotal=0;

    printf("\nGot representative? [Y to continue]: ");
    scanf("%c", &cont);

    while(cont=='y')
    {
        printf("\nRepresentative name : ");
        scanf("%s", name);
        printf("How many companies? : ");
        scanf("%d", &comp);
        tcomp+=comp;
        loop=0;
        total=0;
        do
        {
            printf("Enter amount of donation : ");
            scanf("%f", &donate); loop++;
            total+=donate;
        }
        while(loop<comp);

        printf("%s : %.2f\n", name, total);

        printf("\nGot representative? [Y to continue]: ");
        scanf("%c", &cont);
        gtotal+=total;
    }


    printf("\nTotal Representative : %d", tcomp);
    printf("\nTotal Donations : %.2f\n", gtotal);

    return 0;
}

如你所见:

  1. 您必须在每次询问金额的循环之前重置 loop 变量。
  2. 您必须在该循环之前重置 total
  3. 对于第一个 while 循环的每次迭代,您必须保存到 gtotal
  4. 您必须使用 %c 而不是 %s 来获取单个字符:scanf("%c", &amp;cont);

【讨论】:

  • 我知道我必须对单个字符使用 %c,但由于某种原因,如果我使用 %c,我的代码将在第一个循环之后停止运行。你碰巧知道为什么吗? (我使用代码块)
猜你喜欢
  • 1970-01-01
  • 2021-07-27
  • 2020-08-28
  • 1970-01-01
  • 2021-07-18
  • 2015-02-16
  • 1970-01-01
  • 2021-05-22
  • 2016-02-21
相关资源
最近更新 更多