我是否需要将变量从 main() 模块传递到另一个模块才能获得返回值?

Do I need to pass a variable from the main() module to another module to get a return value?

提问人:Mr. Puli 提问时间:6/2/2023 最后编辑:Mr. Puli 更新时间:6/2/2023 访问量:89

问:

我将在秋天上 c++ 课程,所以我决定做一些自学。我在上个学期上了一门编程逻辑和设计课,一直在写 pusdo 代码。但现在我想把它翻译成 C++。

我写了一个程序来计算超额提取的费用。目标是用它来练习在模块之间传递变量。

我让程序工作,但我想知道我那里是否有额外的代码。我想将变量返回到主程序,而无需将变量从 main() 传递到其他模块。

我需要这两个变量才能使我的程序正常工作吗?

double account余额=0; double overDrawn=0;如果你们有任何其他提示让我的代码更干净,请告诉我。谢谢!

#include <iostream>
#include <cmath>

using namespace std;
// Page 83
// Exercise 5
// The program determines a monthly checking account fee. 
//Declaration of all the modules
int acctBalInput(double acct);
int overdrawInput(double draw);
int feeCalculation(int bal, int draw);
void display(int bal, int draw, int fee);
//Main function
int main()
{
     //Declarations
    double accountBalance=0;
    double overDrawn=0;
    double balance;
    double drawn;
    double totalFee;
    balance = acctBalInput(accountBalance);
    drawn = overdrawInput(overDrawn);
    totalFee = feeCalculation(balance, drawn);
    
    display(balance, drawn, totalFee);
    return 0;

}

//Input account balance.
int acctBalInput(double acct)
{

    cout << "Enter account balance: ";
    cin >> acct;
    return acct;

}

//Input overdrawn times.
int overdrawInput(double draw)
{ 

    cout << "Enter the number of times over drawn: ";
    cin >> draw;
    return draw;

}

//Calculates the total fee.
 int feeCalculation( int bal, int draw)
 {

    int fee;
    int feePercent = 0.01;
    int drawFee = 5;

    fee =(bal*feePercent)+(draw*drawFee);
    return fee;
 }

 //Displays all the ouput.
 void display(int bal, int draw, int fee)
 {

    cout <<"Balance: "<< bal<< endl
    <<"Overdrawn: "<< draw << endl
    <<"Fee: " << fee << endl;
    return;

 }

我尝试在谷歌上搜索,以找到更好的方法来编写代码。

C++ 变量 模块

评论

2赞 Nathan Pierson 6/2/2023
请注意,“模块”在 C++ 中具有特定的含义。你说的是功能。为什么要避免将变量传递给函数并从函数返回值?这是一件很正常的惯用事。
1赞 Nathan Pierson 6/2/2023
另请参阅此处,了解为什么应将代码作为文本而不是图像发布。
1赞 Nathan Pierson 6/2/2023
关于你的代码的一些一般评论:实际上根本没有使用他们的论点。你为什么要向他们传递论点?你可以让它们返回局部变量。其次,小心混合和.使用浮点变量正确处理货币可能很棘手,但您当前的代码只会在我不确定您是否打算的地方将一堆东西四舍五入到最接近的美元值。acctBalInputoverdrawInputintdouble
1赞 user4581301 6/2/2023
注意:除非你对 C++ 基础知识有足够的了解,能够识别白痴和欺诈行为,否则谷歌搜索代码是充满风险的。白痴的数量比专家多出大约 10:1,所以如果你尝试在线学习,你更有可能发现自己向白痴学习。这是一本好书清单注意:正是 Stackoverflow 的内容评级系统和对内容的主动管理,使其成为一个有用且普遍值得信赖的互联网信息来源,并为其赢得了毒性的声誉。白痴通常不喜欢被告知他们是白痴。
2赞 Nathan Pierson 6/2/2023
@Mr.Puli 请看这个演示。我冒昧地将一些变量更改为 s。我还更改了不用于局部变量的参数,并从中删除了现在多余的局部变量。我还切换到在定义变量的位置初始化变量,而不是定义它们,然后在后面的一行中初始化它们。doublemain

答: 暂无答案