c - 如何在 while 循环内重置 do while 循环?

标签 c loops while-loop do-while

#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 和 do while 循环。

最佳答案

位于更正后的代码下方。

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", &cont);

关于c - 如何在 while 循环内重置 do while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32645548/

相关文章:

c - 如果循环外没有 printf,for 循环中的 Printf 将无法工作

PHP 是否可以在 while 循环中为每个 POST 表单发送唯一的值?

c++ - 如何在c/c++中从MySQL获取记录?

c - 在 Visual Studio 中放置要用作命令行参数的文件的位置

c++ - 计算数组中唯一字符的函数

JavaScript 在 PHP 循环中不起作用

java - Java 中 "while"的问题

c - 在 openssl/sha.h 中声明但在共享库中找不到的函数

c - 将新字符串值分配给 char 数组时出错

java - 将文本中写入的数字相加所需的循环