当我通过变量将一个整数传递给下面的函数时(即x = 1 PrintAccntInfo( x, bank_name)
,无论其实际值是什么,它总是被函数读为0。但是,如果我直接键入值,即PrintAccntInfo(1, bank_name)
功能正常。有人可以向我解释这里发生了什么吗?谢谢!
void Bank::PrintAccntInfo(int accntnum, Bank bank_name) {
int num_transactions = 0;
transaction_node *temp;
temp = bank_name.accounts[accntnum].head;
.......
accntnum就是问题所在。
编辑:
这是我调用函数的代码(resp是从用户读入的字符串):
if (stoi(resp)) {
int resp_int = stoi(resp);
if (resp_int = 0) {
for (int i=1;i<21;i++) //print all the account transactions
PrintAccntInfo(i,our_bank);
badinputchk = false;
} else {
PrintAccntInfo(resp_int,our_bank);
badinputchk = false;
}
}
答案 0 :(得分:3)
你在函数中总是得到0的原因是条件
if (resp_int = 0)
将resp_int
设置为0并计算为false
,因此它总是进入“else”,其中使用resp_int(为0)调用该函数
您应该将其替换为if (resp_int == 0)
答案 1 :(得分:0)
我认为x的值超出了范围。你可以更好地展示如何调用函数PrintAccntInfo()和x的定义。
答案 2 :(得分:0)
请注意变量具有“范围”。
int i = 10;
int func(int i) {
if (i > 0) {
int i = 23 + i;
std::cout << "inside func, inside the if, the i here is " << i << std::endl;
}
return i;
}
int main() {
int i = 15;
if (i == 15) {
int i = func(100);
std::cout << "in this part of main, i is " << i << std::endl;
}
std::cout << "But in the end, the outer i is " << i << std::endl;
}