gpt4 book ai didi

c++ - "i"在当前上下文中不可用

转载 作者:搜寻专家 更新时间:2023-10-31 00:59:48 25 4
gpt4 key购买 nike

我第一次尝试调试工具,遇到了以下问题:

当我使用调试器一步一步地检查代码时,当我进入函数 ComputeInterest() 并监视 i 时(标记 i 然后右击它),watch 告诉我

'i' is not available in current context

我也很好奇为什么 watch 没有将 i 放入局部变量中。这是我的代码:

#include <iostream>

double computeInterest (double base_val, double rate, int years)
{
double final_multiplier;
for ( int i = 0; i < years; i++ )
{
final_multiplier *= (1 + rate);
}
return base_val * final_multiplier;
}

int main ()
{
double base_val;
double rate;
int years;
cout << "Enter a base value: ";
cin >> base_val;
cout << "Enter an interest rate: ";
cin >> rate;
cout << "Enter the number of years to compound: ";
cin >> years;
cout << "After " << years << " you will have " << computeInterest( base_val, rate, years ) << " money" << endl;
}

我使用的是 Code:Blocks 的最新版本 13.12、g++ (GCC) 4.8.1 和 GNU gdb (GDB) 7.6.1。

最佳答案

i 被定义并仅存在于该范围内(for 循环):

 for ( int i = 0; i < years; i++ )
{
final_multiplier *= (1 + rate);
}

因此,一旦您进入这些行之一,您将能够检查“i”。一旦你退出这个循环,i 将再次不可用。

编辑:

确保您构建时没有优化 (-O0) 并且带有调试信息 (-g) 编译标志。

编辑 2:

也可能是 GDB 问题。因为我也使用 GDB v7.5.1,如果我没记错的话,并且有相同的行为。也许在更高版本的 GDB 上你会得到预期的行为。作为Baum mit Augen在下面的评论中提到,GDB v7.9 的行为符合您的预期。

关于c++ - "i"在当前上下文中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32657703/

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