c++ - 程序输出 "Heads"而不管随机生成的答案

标签 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;
 }
}

最佳答案

你需要==,而不是=

= 是赋值 == 是比较。

发生的事情是

toss = 1

将值 1 分配给抛掷。然后将其评估为 bool 值,解析为真。所以你总能得到正面。

关于c++ - 程序输出 "Heads"而不管随机生成的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16266745/

相关文章:

c++ - 如何从 C 中的第二行读取字符串文件?

c# - 使用 C++ 向 COM 公开托管事件

c++ - SDL: Blitting BMP to window surface 黑屏之谜

python - 如果 key 在 Python 中包含子字符串

javascript - 如何保存/读取 HTML 中随机打开页面的 cookie 信息?

python-3.x - 使用随机整数和跨列的有限总和创建 pandas 数据框

c++ - 通过 cmd 同时运行 2 个或更多属于不同测试套件的 boost 测试用例

c# - 异常或 If/Else 语句

在 c 中使用 #if 创建程序模式

python - 在python中组织Counter()显示?