当我尝试在 C++ 程序中计算方程式时,我要么得到 0,要么得到 4.94066e-324 [已关闭]

问题描述 投票:0回答:2

该计划的目的是添加 3 种不同的锻炼,以获得举重运动员的总数。我遇到的问题是我的结果始终是 0 或 4.940663-324。我以前做过很多这样的程序,但已经有一段时间了。我相当确定我编码正确,但我将发布我的程序以供审查。

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    
float max_squat, max_bench, max_deadlift, total;

    cout << "Enter your max squat. " << endl;
    cin >> max_squat;
    
    cout << "Enter your max bench press. " << endl;
    cin >> max_bench;
    
    cout << "Enter your max deadlift. " << endl;
    cin >> max_deadlift;
    
    cout << "Your powerlift total is: " << total << endl;
    
    total = max_squat + max_bench + max_deadlift ;

    return 0;
    
}

我尝试将变量类型从 int、float 和 double 更改,但这只会将结果从 0 更改为 4.9....

我还尝试使用 {} 来分离方程,但这不是问题。

我尝试了不同的变量名称和不同的间距/格式,但这没有帮助

经过一些研究,我相信我的问题是我的变量没有被启动?但我不太确定这意味着什么或如何解决它。

c++ variables sum initialization equation
2个回答
0
投票

马克西是正确的。您正在打印一个尚未分配值的变量。

您的代码块应如下所示:

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    
float max_squat, max_bench, max_deadlift, total;

    cout << "Enter your max squat. " << endl;
    cin >> max_squat;
    
    cout << "Enter your max bench press. " << endl;
    cin >> max_bench;
    
    cout << "Enter your max deadlift. " << endl;
    cin >> max_deadlift;

    total = max_squat + max_bench + max_deadlift;
    
    cout << "Your powerlift total is: " << total << endl;

    return 0;
    
}

此外,为了防止将来出现这种情况并帮助避免打印/操作内存中的垃圾(这会使调试更大的程序变得非常困难),您可以考虑初始化变量。例如:

float max_squat = 0, max_bench = 0, max_deadlift = 0, total = 0;

0
投票

您在他具有某些价值之前就打印了总数。

这样做:

total = max_squat + max_bench + max_deadlift ;

并且只有在这之后:

cout << "Your powerlift total is: " << total << endl;
© www.soinside.com 2019 - 2024. All rights reserved.