jkl*_*ara 0 c++ random if-statement 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;
}
}
Run Code Online (Sandbox Code Playgroud)
你需要==,而不是=
=是赋值==是比较.
会发生什么事
toss = 1
Run Code Online (Sandbox Code Playgroud)
将值1赋予折腾.然后将其评估为布尔值,该值将解析为true.所以你总能得到满足.