gpt4 book ai didi

c++ - 我无法访问我的变量的值,即使我通过作用域传递了它

转载 作者:行者123 更新时间:2023-11-27 22:37:37 25 4
gpt4 key购买 nike

首先我想说我是 C++ 的新手。我一直在从网站上学习,并尝试了几个小时来改组我的代码并尝试新事物以试图解决这个问题。

当我在变量被修改的函数中引用变量时,它返回正确的值。一旦离开该函数,即使我已将变量传递给下一个函数,值也会被重置。我什至开始到处添加 cout 来显示值以帮助我调试,但没有产生任何结果。有人可以指出我正确的方向吗?我将在下面发布我的代码。感谢您的帮助,伙计们。

#include <iostream>

//void Loop(int Total, int Spend);
//int NewTotal(int Total, int Spend);
//void Spent(int Total, int Spend);
void UserInput(int Total, int Spend);

// Loops back to UserInput() for next entry input
void Loop(int Total, int Spend)
{
UserInput(Total, Spend);
}

int NewTotal(int Total, int Spend)
{
std::cout << "Output of Total is: " << Total << std::endl;
std::cout << "Output of Spend is: " << Spend << std::endl;
return Total + Spend;
}

void Expense()
{
std::cout << "Please enter a description of your expense!" << std::endl;
char ExpenseDesc;
std::cin >> ExpenseDesc;
std::cout << "You described your expense as: " << std::endl;
std::cout << ExpenseDesc << std::endl;
}

void Spent(int Total, int Spend)
{
std::cout << "Please enter the amount you spent!" << std::endl;
std::cin >> Spend;
NewTotal(Total, Spend);
}

void UserInput(int Total, int Spend)
{
Expense();
Spent(Total, Spend);
std::cout << "Result of Total and Spend (NewTotal) is: " << Total + Spend << std::endl;
std::cout << "Record saved!" << std::endl;
std::cout << "So far, you have spent " << NewTotal(Total, Spend) << "!" << std::endl; //int Total & int Spend not retaining value when NewTotal(Total, Spend) gets called again to return value
std::cout << "Ready for next entry!" << std::endl;
Loop(Total, Spend);
}

int main()
{
int Total;
int Spend;
Spend = 0;
Total = 0;
UserInput(Total, Spend);
return 0;
}

本质上,这是一个非常基本的提示,要求您提供交易描述(只接受一个字符,我需要修正)和交易金额。完成该条目后,您可以再输入一个条目,程序应该将旧总数添加到新总数以得出到目前为止的总支出,然后重复提示。

最佳答案

您需要通过引用传递变量或从函数中返回它们。就目前而言,您正在为每个函数创建局部变量的拷贝,修改拷贝,然后在作用域结束时丢弃它们。

返回值:

std::pair<int, int> Spent(int Total, int Spend) {
...
return std::make_pair(Total, Spend);
}

// Getting values out
std::pair<int, int> result = Spent(Total, Spend);
int newTotal = result.first;
int newSpend = result.second;
// or
int newTotal, newSpend;
std::tie(newTotal, newSpend) = Spent(Total, Spend);
// or (C++17)
auto [newTotal, newSpend] = Spent(Total, Spend);

引用参数:

void Spent(int& Total, int& Spend) {
// Modifications to Total and Spend in this function will apply to the originals, not copies
...
}

关于c++ - 我无法访问我的变量的值,即使我通过作用域传递了它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52257887/

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