gpt4 book ai didi

c++ - 未初始化的局部变量

转载 作者:搜寻专家 更新时间:2023-10-31 01:34:55 26 4
gpt4 key购买 nike

我是新手,刚开始学习 C++,遇到了这个问题,我可能花了一个小时试图修复和研究答案,但我似乎无法弄清楚我做错了什么。我使用 Visual Studios 作为我的 IDE,这是最新版本。

#include "stdafx.h"
#include <iostream>
#include "constant.h"

//height of the tower
double towerHeight(double x)
{
using namespace std;
cout << "Enter a height for the tower" << '\n';
cin >> x;

return x;
}

//the number of seconds since the ball has been dropped to determine the distance
double secondsSinceDrop(double x)
{
using namespace std;
cout << "How long has it been since you dropped the ball (Seconds): ";
cin >> x;

return x;
}

//finds how far off the ground the ball is
double currentBallHeight(double x, double y)
{
return y * constant::gravity - x;
}

//prints how far off the ground the ball is
void printResult(double x, double y)
{
using namespace std;
if (currentBallHeight(x, y) < 0)
cout << "At " << y << " the ball is on the ground." << '\n';
else
cout << "At " << y << " the ball is at: " << currentBallHeight(x, y) << '\n';
}

int main()
{
double x = towerHeight(x);
double y = secondsSinceDrop(x);

printResult(x,y);

return 0;
}

这是错误代码- 第 2 章综合测验(第 2 部分).cpp(46):错误 C4700:使用了未初始化的局部变量“x”

-第(46)行是-double x = towerHeight(x);

我一直遇到这个问题,我已经更改了我的代码以将其归结为这个错误,但我不知道如何修复它。它可能很简单,我很愚蠢地忽略了它,但我们将不胜感激任何帮助。

最佳答案

These lines will be throwing errors
because the variable 'x' you are sending as an argument does not exist in the scope of main

 int main()
{
-> double x = towerHeight(x);
-> double y = secondsSinceDrop(x);

printResult(x,y);

return 0;
}

相反,您可以尝试这样的事情。

#include "stdafx.h"
#include <iostream>
#include "constant.h"
using namespace std;

//height of the tower
double towerHeight()
{
double height;
cout << "Enter a height for the tower" << '\n';
cin >> height
return height;
}

//the number of seconds since the ball has been dropped to determine the distance
double secondsSinceDrop()
{
double seconds;
cout << "How long has it been since you dropped the ball (Seconds): ";
cin >> seconds;
return seconds;
}

//finds how far off the ground the ball is
double currentBallHeight(double x, double y)
{
return y * constant::gravity - x;
}

//prints how far off the ground the ball is
void printResult(double x, double y)
{
if (currentBallHeight(x, y) < 0)
cout << "At " << y << " the ball is on the ground." << '\n';
else
cout << "At " << y << " the ball is at: " << currentBallHeight(x, y) << '\n';
}

int main()
{
double height = towerHeight();
double seconds = secondsSinceDrop();

printResult(height, seconds);

return 0;
}

一些我会推荐的技巧

  • Declare your variables as much as relevant to you instead of using 'x/y/z'
  • There is no need to add the using namespace std; inside each function

关于c++ - 未初始化的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38365779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com