无论随机生成的答案如何,程序输出“Heads”

时间:2013-04-28 19:18:22

标签: c++ if-statement random output

我是C ++的新手并且想知道为什么无论生成的随机数是什么,输出总是头。我假设函数默认为第一个if语句是读取,但我不知道如何在输出文本之前检查它们。提前致谢。

#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
int coinToss(int);
int main()
{
 int input;
 int counter;
 int toss;
 int check;
 cout<<"Enter the number of times the coin will be tossed:";
 cin>>input;
 coinToss(input);
 system("PAUSE");
 return 0;
}

int coinToss(int input)
{
 int toss;
 int counter = 1;
 while(counter<=input)
 {
  toss = rand() % 2 + 1;
  int check = toss;
  cout<<check<<endl;
  if (toss = 1)
  {
  cout<<"Heads"<<endl;
  }
  else if (toss = 2)
  {
  cout<<"Tails"<<endl;
  }
  counter += 1;
 }
}

3 个答案:

答案 0 :(得分:5)

你需要==,而不是=

=是作业 ==是比较。

会发生什么

toss = 1

将值1分配给折腾。然后将其评估为布尔值,该值将解析为true。所以你总能得到头脑。

答案 1 :(得分:4)

这是 assigment 而非等同性检查:

if (toss = 1)

导致toss设置为1,分配结果为1,这意味着始终输入if分支。使用==

if (toss == 1)

if else条件的错误相同。

请注意,该程序具有未定义的行为,因为coinToss()未返回int但返回类型为int

int coinToss(int input)
{
    // no return!
}

返回类型void或返回int

答案 2 :(得分:2)

以下是作业,而不是比较:

if (toss = 1)

将其更改为

if (toss == 1)

toss = 2同样如此。

最好在gcc中启用编译器警告(-Wall)。大多数优秀的编译器会警告你错误的任务。