在循环外声明的变量在c++中是不确定的
Variable declared outside of a loop is unidentified inside C++
我有一个用Microsoft Visual Studio编写的c++程序(我刚刚开始学习)。下面是我的代码:
else
// time is in seconds
int time = 0;
double speed = 0.0;
while (height >= 0)
{
cout << "At " << int time << " secs the ball is at height: " << height << " metres.n";
time++;
height -= distanceTravelled(speed);
speed += gravity;
}
// If height dropped from positive to negative in one second, the final fraction of a
// second before it hits the ground isn't displayed - so the if statement
if (height <= 0)
cout << "At " << time << " secs the ball is at height: " << height << " metres.n";
当我试图构建它时,我得到一个错误
"time"是一个未声明的标识符。
但是我在while循环之外声明了它。那为什么找不到呢?
您发布的代码中有两个问题。一个是输出线上的伪int
。它应该是这样的:
cout << "At " << time << " secs the ball is at height: " << height << " metres.n";
第二个问题是你的else
缺少大括号。这意味着只有time
的声明在else
分支中,其他所有内容都与条件处于同一级别(缩进在c++中不计算)。所以它应该是这样的:
else
{
// time is in seconds
int time = 0;
double speed = 0.0;
while (height >= 0)
{
cout << "At " << time << " secs the ball is at height: " << height << " metres.n";
time++;
height -= distanceTravelled(speed);
speed += gravity;
}
// If height dropped from positive to negative in one second, the final fraction of a
// second before it hits the ground isn't displayed - so the if statement
if (height <= 0)
cout << "At " << time << " secs the ball is at height: " << height << " metres.n";
}
问题是您在cout语句中声明了一个新变量:
cout & lt; & lt;"At"<<int time <<当球在高处时:<<高度& lt; & lt;"米。 n";
去掉int
你的问题就在这里:
else //<==== missing paranthesis
// time is in seconds
int time = 0;
double speed = 0.0;
在else之后缺少一个左括号。实际上,else之后的第一个语句是if-else语句的假分支。在那之后的就不是。因此,在double speed = 0.0;之后的所有代码都在if语句之外,这在代码摘录中是不可见的。
这实际上使得int time处于完全不同的作用域,而不是下面访问这个的代码。这就是为什么访问int time变量的代码找不到它的原因。
修复:在else之后添加{,并在下面添加}以包含您的逻辑
这一行有问题。
cout << "At " << int time << " secs the ball is at height: " << height << " metres.n";
int time
在这里应该只替换为time
。
Datatype仅在定义变量(如int time
)或强制转换变量(如(int)time
)时使用变量指定。您只是打印一个int
变量。
我无法重现您在g++编译器中遇到的完全相同的错误,但更改上述内容可能会解决此问题。
相关文章:
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 不确定如何装饰我的C++库代码以在 C 中使用
- C++功能泄漏内存,我是C++新手,不确定如何解决
- "错误 C0000:语法错误,令牌"<EOF>"处出现意外$end,并且不确定
- 代码在 CodeSignal 中工作不正确。不确定这是否是我的代码缺陷
- 为什么以下代码是不确定的?
- 编译错误:"lvalue required as left operand of assignment" 不确定原因
- 误用指针会产生分段错误。我仍然不确定如何纠正它
- 我不确定为什么代码没有运行,它在编译时抛出错误,说它无法找到 PrintArray()
- 不确定出了什么问题(字符串输入)
- C++睡眠时间不确定
- 在C++中做一个场景问题,我不确定如何处理布尔和if循环
- 代码输出随机符号,我不确定出了什么问题
- 可变值变化,不确定原因
- 有没有办法让C++从 cin 中接收不确定数量的字符串?
- 尝试一次将单个字符读取到大小不确定的数组中
- 我不确定如何引用此神经网络训练方法中的权重
- 函数参数:不确定排序还是未排序?
- std::random_device如何生成不确定的随机数?
- 不确定有关入门C++参考的描述