【问题标题】:void function Math error无效函数数学错误
【发布时间】:2013-10-13 14:57:49
【问题描述】:
#include <iostream>

using namespace std;

void compute_coins(int change, int quarters, int dimes, int nickels, int pennies);
void output(int quarters, int dimes, int nickels, int pennies);

int main()
{
  int change, quarters, dimes, nickels, pennies;
  char again = 'y';

  cout << "Welcome to the change dispenser!\n";

  while(again == 'y'){//Creating loop to allow the user to repeat the process
    cout << "Please enter the amount of cents that you have given between 1 and 99\n";
    cin >> change;
    while((change < 0) || (change >100)){//Making a loop to make sure a valid number is             inputed
        cout << "Error: Sorry you have entered a invalid number, please try again:";
        cin >> change;
    }
    cout << change << " Cents can be given as: " << endl;
    compute_coins(change, quarters, dimes, nickels, pennies);
    output(quarters, dimes, nickels, pennies);

    cout << "Would you like to enter more change into the change dispenser?  y/n\n";//prompts the user to repeat this process
    cin >> again;
  }
  return 0;
}


void compute_coins(int change, int quarters, int dimes, int nickels, int pennies) {//calculation to find out the amount of change given for the amount inpuied
    using namespace std;
    quarters = change / 25;
    change = change % 25;
    dimes = change / 10;
    change = change % 10;
    nickels = change / 5;
    change = change % 5;
    pennies = change;
    return ;
}

void output(int quarters, int dimes, int nickels, int pennies){
  using namespace std;
  cout << "Quarters = " << quarters << endl;
  cout << "dimes = " << dimes << endl;
  cout << "nickels = " << nickels << endl;
  cout << "pennies = " << pennies << endl;
}

抱歉,代码没有很好地传输,我对这个网站还是很陌生。但是,对于季度、硬币、镍和便士的结果,我得到了疯狂的数字。我已经这样做了一次,效果很好,但我没有使用 void 函数,所以我不得不重做它,我把自己搞砸了,我被卡住了。任何帮助表示赞赏!

【问题讨论】:

  • C++ 是按值传递的,除非您指定引用。
  • 具体出了什么问题?到目前为止,您具体尝试了什么?我们很乐意提供帮助,但如果没有一些指导,我们很难回答您的问题。你能用更多细节更新你的问题吗?
  • 如果您允许,您的编译器能够发出有用的警告:coliru.stacked-crooked.com/a/6449ef3601fb9ef4

标签: c++ function math void


【解决方案1】:
void compute_coins(int change, int quarters, int dimes, int nickels, int pennies);

这意味着您只获取传递给函数的值的副本。因此,您在函数中所做的任何事情都不会对您传入的实际值产生任何影响。

void compute_coins(int &change, int &quarters, int &dimes, int &nickels, int &pennies);

这意味着您提供实际变量,而不仅仅是副本。无论您对参数所做的任何更改实际上都是在您传入的变量上完成的。

查找引用和指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-16
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多