我不得不为学校编写一个C ++程序,但我能正常工作,但是我想不出如何使它保持值来显示头被甩和尾被甩的次数。它一直说0。这些是方向:编写一个模拟硬币抛掷的C ++程序。对于每次抛硬币,程序应打印正面或反面。该程序应抛硬币100次。计算硬币每面出现的次数,并在100次抛掷结束时打印结果。
该程序至少应具有以下功能:
void toss()-从main()调用,将随机抛硬币并设置一个等于硬币面的变量 void count()-从折腾调用以增加头或尾的计数器 void displayCount()-从main()调用,将显示正面计数器的值和反面计数器的值。无全球变量!
以下是代码:
#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";
}
答案 0 :(得分:2)
void toss(int headCount, int tailCount)
是pass by value, not reference,因此在toss
中发生的事情留在toss
中。给予
void toss(int &headCount, int &tailCount)
尝试,然后将相同的想法应用于count
。
从更深的角度看,应该在count
的{{1}}循环内调用toss
,否则它将只运行一次。这意味着for
循环的当前胆量需要重新考虑。我会完全放弃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 << "heads\n";
headCount++; //counts the amount of heads
}
else
{
cout << "tails\n"; //assigns 1 to tails
tailCount++; //counts the amount of tails
}
}
}
最好在srand
顶部附近的程序中调用一次。每次您呼叫main
时,它都会重置随机数生成器。如果您再次拨打srand
太快,时间将没有时间更改到下一秒,您将生成相同的数字。在少数情况下,您确实需要每个程序多次调用srand(time(NULL));
,srand
和rand
可能不是完成此任务的正确工具。查看C ++ 11或第三方随机数工具中添加的srand
库。