C编程。硬币翻转程序循环不像我想要的

时间:2016-10-18 02:17:03

标签: c loops for-loop

所以我应该做一个硬币翻转程序,我做了一切正确,但我应该这样做,以便它保持循环,直到用户输入0.我已经这样做,但每次程序循环,头和尾的输出不要重置。我运行程序,它询问我想要翻转硬币的次数,然后我输入5.然后它给我说3个头和2个尾巴,然后再次循环问我同样的问题。我再次输入5,但现在结果是7个头和3个尾巴。但是我只要求将它翻转5次,所以当我想要一个新的计数时,它会将新的头/尾数添加到新的头部/尾部。我很确定这是一个简单的修复,但请帮忙。下面是代码:

for (;;) {

printf("How many times do you want to flip the coin? (Press 0 to exit));
scanf("%d", &toss);                 

if (toss == 0) {
printf("Thank you for using the program!\n");
break;                  //terminates program if toss = 0
}

puts (" ");

for ( counter = 0; counter < toss; counter++ ) 
{
        if (flip( ) == 0)       //call the function flip
        heads++;

        else
        tails++;
}                   //end of for loop

printf( "Heads Was Flipped %d Times\n", heads );
printf( "Tails Was Flipped %d Times\n", tails );

continue;
return 0;

1 个答案:

答案 0 :(得分:1)

在使用变量之前,必须重置head和tail的值。这是代码snippite。     for(;;){

printf("How many times do you want to flip the coin? (Press 0 to exit));
scanf("%d", &toss);                 

if (toss == 0) {
printf("Thank you for using the program!\n");
break;                  //terminates program if toss = 0
}

puts (" ");
heads = 0;//reset value of heads
tails = 0;//reset value of tails

for ( counter = 0; counter < toss; counter++ ) 
{
        if (flip( ) == 0)       //call the function flip
        heads++;

        else
        tails++;
}                   //end of for loop

printf( "Heads Was Flipped %d Times\n", heads );
printf( "Tails Was Flipped %d Times\n", tails );

continue;
return 0;