【问题标题】:C++ strange output when adding integers or doubles together将整数或双精度数相加时的 C++ 奇怪输出
【发布时间】:2013-01-13 17:47:35
【问题描述】:

我在 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;
}

【问题讨论】:

    标签: c++ variables integer double


    【解决方案1】:

    使用前需要先将变量初始化为0,如下图。

    double bowlTotal = 0.0;
    double bowlScore = 0.0;  
    

    通常编译器不会为您执行此操作,并且变量将填充有效的垃圾值,您可以在其中添加分数。

    正如 GManNickG 简洁地说的那样,reading an uninitialized variable is undefined behavior

    【讨论】:

    • 更正式地说,读取未初始化的变量是未定义的行为。
    • 太棒了!谢谢您的帮助!知道这真的很愚蠢,哈哈
    【解决方案2】:

    您没有初始化 bowlTotal 或 bowlScore,所以它们包含垃圾。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      • 1970-01-01
      • 2022-01-12
      • 2017-10-26
      • 2010-10-06
      • 2021-03-10
      相关资源
      最近更新 更多