我是 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/