#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 while循环。
答案 0 :(得分:0)
在更正后的代码下方。
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;
}
如你所见:
loop
变量。total
gtotal
。scanf("%c", &cont);