硬币翻转程序无法运行



该程序将无法运行,任何人都可以帮助我理解原因。这是一个抛硬币游戏,应该询问你想掷硬币的次数,问你是在叫正面还是反面,掷硬币,然后说你的猜测是对还是错

# 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();

问题不在于这段代码"不运行";它甚至不编译。代码中存在许多错误。

  1. numHT()中使用的结果是 H_T() ; 但H_T()返回void
  2. 您试图打破将tosses_amount的值与0进行比较的无限循环;但是tosses_amount被分配了始终大于0tossingtimes()值。
  3. for循环中注释为// random number generator看起来您正在尝试使用heads_win()tails_win()的函数;实际上,您正在用这些名称声明新函数。
  4. 您实际上从未尝试将获得的正面或反面数量与用户输入的数量进行比较。
  5. 你只掷硬币一次(在main()开始时(,并且一遍又一遍地重复使用相同的价值。

还有其他几个错误,但您可以从这些错误开始。

最新更新