c++ - 你好,关于函数的程序(按引用传递/按值传递)我不完全确定我的程序出了什么问题

标签 c++

有人可以就我的程序有什么问题提供建议或指导吗?我确实已经把程序写完了,但我不确定在我的程序中添加函数定义和函数原型(prototype)的位置。该程序涉及按值传递和按引用传递。此外,任何关于小错误的有用通知将不胜感激

#include "pch.h"
#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
    //Declare Variables
    double amount = 22.66;
    int num;
    int dollars;
    int quarters;
    int dimes;
    int nickels;
    int pennies;
    double x = 22.25;
    double y = 55.55;

    //Input
    cout << "Please enter your dollar amount: ";
    cin >> amount;


    void showMenu() //function prototype
    {
        cout << "A. Money Exchange function" << endl;
        cout << "B. Find Max Solution" << endl;
        cout << "E. Exit" << endl;
        cout <<"Please enter your choice:"<<endl;
    }


    void MoneyExchange(float amount, int& dollars, int& quarters, int& dimes, 
    int & nickels, int & pennies)   // function prototype
    {
        int amount = 0, Remainder;
        amount = amount * 100;
        dollars = amount / 100;
        Remainder = amount - (dollars * 100);
        quarters = Remainder / 25;
        Remainder = Remainder - (quarters * 25);
        dimes = Remainder / 10;
        Remainder = Remainder - (dimes * 10);
        nickels = Remainder / 5;
        Remainder = Remainder - (nickels * 5);
        pennies = Remainder / 1;
    }


    double max(double x, double y)  //function prototype
    {
        double max;
        if (x >= y)
            max = x;
        else
            max = y;

        system("Pause");
        return 0;
    }

最佳答案

要使用一个函数,你需要有一个函数方法声明(告诉编译器/链接器这个函数存在)和实现(函数方法做的事情)。 这是一个准系统示例

void doStuff(); //im function declaration/prototype
void doMoreStuff(); //im function declaration/prototype



int main()
{
  void doMoreStuff() //dont nest me in here!
  {
     cout << "doMoreStufff runs" << endl; 
  }
  doStuff();
  doMoreStuff();
  return 1;
}
void doStuff() //im function implementation
{
   cout << "doStuff runs" << endl; 
}

要点: 1) 你在代码中所说的function prototype是函数实现 2) 没有嵌套实现。例如:不要这样做

int main()
{
  void doMoreStuff() //dont nest me in here!
  {
     cout << "doMoreStufff runs" << endl; 
  }
  doStuff();
  doMoreStuff();
  return 1;
}
void doStuff() //im function implementation
{
   cout << "doStuff runs" << endl; 
}

(旁注:可以在其中嵌套匿名/lambda 函数)

3) 在您的情况下,将方法实现坚持在 main{} 实现之上还是之下并不重要,只要确保您的函数在 main{} 之上声明即可实现(使用这些方法的地方)

关于c++ - 你好,关于函数的程序(按引用传递/按值传递)我不完全确定我的程序出了什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53509757/

相关文章:

c++ - 在 C++ 中与数组串联?

c++ - G++ 4.5 错误 : No diagnostic for narrowing in initializer list

c++ - 在其他函数模板、参数中使用推导类型

c++ - zeroMQ:zmq_recv() 不起作用

c++ - 为什么我的浮点值会失去精度并丢掉小数位?下面的示例代码

c++ - 调用重载的 to_string 不明确

c++ - 多参数树遍历

c++ - 使用 C 语言通过贝塞尔曲线平滑粗糙多边形的算法

C++ new int[0]——它会分配内存吗?

c++ - MFC 在对话框中找不到 GetDocument()