显示时间的正面和反面被扔C++

display amount of time heads and tails was tossed C++

本文关键字:C++ 显示 时间      更新时间:2023-10-16

我不得不为学校编写一个C++程序,我让它工作,但我无法弄清楚如何让它保持值以显示正面被抛出和反面被抛出的次数。它一直说0。这些是方向:编写一个模拟抛硬币的C++程序。 对于每次抛硬币,程序应打印正面或反面。 程序应该抛硬币 100 次。 计算硬币每面出现的次数,并在100次掷出结束时打印结果。

该程序至少应具有以下功能:

void toss(( - 从main((调用,将随机抛硬币并设置一个等于硬币表面的变量 void count(( - 从投掷到正面或反面的增量计数器调用 void displayCount(( - 从main((调用,将显示头部计数器的值和 tails.NO GLoBAL变量的计数器值!!

以下是代码:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
//prototypes
void toss(int headCount, int tailCount);
void count(int headCount, int tailCount);
void displayCount(int headCount, int tailCount);
//tosses a coin 100 itmes and tells you how many were heads and how many were tails.
int main()
{
int headCount = 0;
int tailCount = 0;
int count = 0;
toss(headCount, tailCount);  //toss coin
displayCount(headCount, tailCount); //displays how many heads and tails
}
//***************function definitions***************
void toss(int headCount, int tailCount)
{
srand(time(NULL));//makes the coin toss random
for (int i = 0; i<100; i++)  //while it is less then 100 tosses
{
if (rand() % 2 == 0)   //assigns 0 to heads
{
cout << "heads";
}
else
{
cout << "tails";  //assigns 1 to tails
}
}
count(headCount, tailCount);
}
void count(int headCount, int tailCount)
{
if (rand() % 2 == 0)
{
headCount++;    //counts the amount of heads
}
else
{
tailCount++;   //counts the amount of tails
}
}
void displayCount(int headCount, int tailCount)   //displays count of head and tails
{
cout << "Number of heads: " << headCount << "n";
cout << "Number of tails: " << tailCount << "n";
}   
void toss(int headCount, int tailCount)

是按值传递的,而不是引用的,所以toss中发生的事情会保留在toss中。给

void toss(int &headCount, int &tailCount)

尝试一下,然后将相同的思维应用于count.

更深入地观察,count应该在tossfor循环中调用,否则它只会运行一次。这意味着需要重新考虑for循环的当前内部。我会完全放弃count函数并使用类似的东西:

void toss(int &headCount, int &tailCount)
{
srand(time(NULL));//makes the coin toss random. 
// Well... Sorta. More on that in a second.
for (int i = 0; i<100; i++)  //while it is less then 100 tosses
{
if (rand() % 2 == 0)   //assigns 0 to heads
{
cout << "headsn";
headCount++;    //counts the amount of heads
}
else
{
cout << "tailsn";  //assigns 1 to tails
tailCount++;   //counts the amount of tails
}
}
}

还有一个旁注:

srand最好在程序靠近main顶部的地方调用一次。每次调用srand时,它都会重置随机数生成器。如果您再次呼叫srand(time(NULL));太快,时间将没有时间更改为下一秒,您将生成相同的号码。在少数情况下,您确实需要为每个程序多次调用srandrandsrand可能不是适合这项工作的工具。查看 C++11 或第三方随机数工具中添加的<random>库。