在循环外声明的变量在c++中是不确定的

Variable declared outside of a loop is unidentified inside C++

本文关键字:不确定 c++ 变量 声明 循环      更新时间:2023-10-16

我有一个用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++编译器中遇到的完全相同的错误,但更改上述内容可能会解决此问题。