私はルーレットのような C++ コマンドライン プログラムを書いています。ユーザーは、賭けのために小数値/数字を入力することができます。これを可能にするために double 型の変数を使用しています。しかし、たとえば 1 ドルから始めて、0.23 ドルを賭けて負け、次に 0.55 ドルを賭けて負け、0.07 ドルを賭けてまた負けた場合、実際には 0.15 ドル持っているとプログラムが主張していても、0.15 ドルを賭けることはできません。ドル (持っている以上のお金を賭けることはできません)。プログラムが間違って減算しているようです。しかし、私はまだ 0.149 ドルを賭けることができます。価値があるのは、stringstream を使用して、ユーザーの賭けの入力を double 型の値に変換することです。誰かがここで何が起こっているのか説明できますか?
これが私のコードです:
#include <iostream>
#include <sstream>
using namespace std; //Std namespace.
void string_to_number(string input, double& destination);
class Roulette {
private:
int randoms;
double money, choice, bet;
string input;
public:
int play = 0;
void start_amount() {
cout<<"How much money do you have?: ";
getline(cin, input);
string_to_number(input, money);
}
void betting() {
cout<<"How much money would you like to bet?: ";
getline(cin, input);
string_to_number(input, bet);
while (bet > money) {
cout<<"You can't bet more money than you have ("<<money<<" dollars). Please enter again: ";
getline(cin, input);
string_to_number(input, bet);
}
}
void choose_number() {
cout<<"Which number do you choose? (0-35): ";
getline(cin, input);
string_to_number(input, choice);
}
void random_number() {
cout<<"The wheel is spinning..."<<endl<<flush;
randoms = (rand())%36;
}
void scenarios() {
cout<<"The wheel shows number "<<randoms;
if (randoms == choice) {
money += bet;
cout<<", which means that you win "<<bet<<" dollars! You currently have "<<money<<" dollars."<<flush<<endl;
}
else {
money -= bet;
cout<<", which means that you lose "<<bet<<" dollars. You currently have "<<money<<" dollars."<<flush<<endl;
}
}
};
int main(int argc, const char * argv[])
{
srand(unsigned(time(0)));
Roulette a;
a.start_amount();
while (a.play == 0) {
a.betting();
a.choose_number();
a.random_number();
a.scenarios();
}
return 0;
}
void string_to_number(string input, double& destination) {
stringstream convert(input);
if ( !(convert >> destination) )
destination = 0;
}