C 编程。硬币翻转程序循环没有像我想要的那样工作

标签 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;

最佳答案

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

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;

关于C 编程。硬币翻转程序循环没有像我想要的那样工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40098481/

相关文章:

c - 我如何使用 strace 了解我的 C 程序中的系统调用

c - 循环平铺优化

ios - 如何用for循环添加多个字典?

java - 使用foreach循环构造数组中的对象

scala - 将 'for' 循环从 Java 重写为 Scala

c - 编译文件(汇编文件)中的头文件信息在哪里?

c - 在C中的地址位置存储一个字符

php - 在我的 php 脚本中为 loop() 消除这一层

c++ - 推送 Lua 表

javascript - 我想创建猜谜游戏,用户应该在提示中输入正确的颜色