我遇到了在c ++中添加数字类型的问题,并且无法弄清楚为什么会发生这种情况,我希望当我输入3个保龄球分数时我会得到9或9.00,而不是像3.31748e + 258那样疯狂的东西,什么我做错了吗?任何帮助都会有很长的路要谢!
#include<iostream>
#include<cmath>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
using namespace std;
int main()
{
/*Coordinate variables*/
double bowlTotal;
double bowlScore;
const int FIVE_PLAYERS = 5;
for( int players = 0; players < FIVE_PLAYERS ; players++ )
{
cout << "Player " << players + 1 << endl << endl;
for( int games = 0; games < 3; games++ )
{
double score;
score = 0;
cout << "Please enter score for game #" << games + 1<< ": ";
cin >> score;
cout << endl;
bowlTotal += score;
}
cout << endl << endl <<"The final score for player #"<< players + 1 << " = " << bowlTotal << endl << endl;
bowlScore += bowlTotal;
}
cout << endl << endl <<"The final team score = " << bowlScore << endl << endl;
system("PAUSE");
return 0;
}
答案 0 :(得分:7)
您需要在使用之前将变量初始化为0,如下所示。
double bowlTotal = 0.0;
double bowlScore = 0.0;
通常,编译器不会为您执行此操作,并且变量将填充有效垃圾值,您可以在其中添加分数。
正如GManNickG所说,reading an uninitialized variable is undefined behavior。
答案 1 :(得分:2)
您没有初始化bowlTotal或bowlScore,因此它们包含垃圾。