该程序将无法运行,任何人都可以帮助我理解原因。这是一个抛硬币游戏,应该询问你想掷硬币的次数,问你是在叫正面还是反面,掷硬币,然后说你的猜测是对还是错
# include <iostream>
# include <ctime>
# include <cstdlib>
# include <string>
using namespace std;
int tossingtimes()
{
int tosses;
cout << "How many tosses will we attempt? " << endl;
cin >> tosses;
while(tosses < 1)
{
cout << "Error tosses must be greater than or equal to 1. Please submit a correct answer." << endl;
cin >> tosses;
}
return tosses;
}
void H_T ()
{
char HT;
cout << "Will you be guessing heads or tails? ('h' or 't')";
cin >> HT;
if ( HT = 'h')
{
cout << "You chose to select Heads!";
}
else
{
cout << "You chose to select Tails!";
}
}
int numHT ()
{
int num;
cout << "How many times will " << H_T () << "come up?";
cin >> num;
return num;
}
int head_win ()
{
int heads=0;
heads++;
return heads;
}
int tails_win ()
{
int tails=0;
tails++;
return tails;
}
int main()
{
srand((unsigned) time(0));rand();
int result = rand() % 2;
while (true)
{
int tosses_amount, HT, num;
tosses_amount = tossingtimes();
H_T ();
num = numHT();
cin.ignore (1000, 10);
if (tosses_amount == 0)
break;
for (int i = 0; i < tosses_amount; i++)
//random number generator
{
if (result == 0)
{
int head_win();
cout << "Heads" << endl;
}
else if (result == 1)
{
int tails_win();
cout << "Tails"<<endl;
}
}
}
system ("pause");
return 0;
}
我看到的一个明显的问题是:
void H_T() {
// ...
}
// ...
cout << "How many times will " << H_T() << "come up?";
这尝试从H_T
中打印出返回值,但由于H_T
具有 void 返回类型,因此没有这样的事情,编译将失败。
浏览代码,看起来这几乎不是唯一的代码。我想如果我是你,我会备份并或多或少地重新开始。一次写一小段,并在进入下一个之前验证每个片段是否符合您的意图。
在void H_T()
中,你有:
if ( HT = 'h')
将值'h'
分配给将始终计算为 true 的HT
。您希望==
改为测试相等性。
不幸的是,您不会跟踪用户在代码中任何地方选择的内容......
乍一看..
int head_win ()
{
int heads=0;
heads++;
return heads;
}
int tails_win ()
{
int tails=0;
tails++;
return tails;
}
head_win(( 将始终返回 1 和 tails_win((。
int head_win(); this doesn t mean nothing..
你必须声明一个变量:
int wins = head_win();
问题不在于这段代码"不运行";它甚至不编译。代码中存在许多错误。
- 在
numHT()
中使用的结果是H_T()
; 但H_T()
返回void
。 - 您试图打破将
tosses_amount
的值与0
进行比较的无限循环;但是tosses_amount
被分配了始终大于0
的tossingtimes()
值。 - 在
for
循环中注释为// random number generator
看起来您正在尝试使用heads_win()
和tails_win()
的函数;实际上,您正在用这些名称声明新函数。 - 您实际上从未尝试将获得的正面或反面数量与用户输入的数量进行比较。
- 你只掷硬币一次(在
main()
开始时(,并且一遍又一遍地重复使用相同的价值。
还有其他几个错误,但您可以从这些错误开始。