我必须创建一个将执行所有处理的函数(billsHundred到coinLoonie计算),但输入和输出到控制台仍将在int main中完成。我该怎么做呢我真的遇到了从函数int cash()生成多个输出的问题,所以我把它留空,以便看看你们的建议。
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int cash();
int main()
{
int dollarAmount;
for (int i = 1; i <= 3; i++)
{
cout << "Enter the total dollar amount: $";
cin >> dollarAmount;
while (cin.fail())
{
cout << "\nThat entry is not valid. Please try again: ";
cin.clear();
cin.ignore(1000, '\n');
cin.clear();
cin >> dollarAmount;
}
int billsHundred = dollarAmount / 100;
int billsFifty = (dollarAmount - (100 * billsHundred)) / 50;
int billsTwenty = (dollarAmount - (100 * billsHundred) - (50 * billsFifty)) / 20;
int billsTen = (dollarAmount - (100 * billsHundred) - (50 * billsFifty) - (20 * billsTwenty)) / 10;
int billsFive = (dollarAmount - (100 * billsHundred) - (50 * billsFifty) - (20 * billsTwenty) - (10 * billsTen)) / 5;
int coinToonie = (dollarAmount - (100 * billsHundred) - (50 * billsFifty) - (20 * billsTwenty) - (10 * billsTen) - (5 * billsFive)) / 2;
int coinLoonie = (dollarAmount - (100 * billsHundred) - (50 * billsFifty) - (20 * billsTwenty) - (10 * billsTen) - (5 * billsFive) - (2 * coinToonie)) / 1;
cout << "\nNumber of 100$ bills = " << billsHundred;
cout << "\nNumber of 50$ bills = " << billsFifty;
cout << "\nNumber of 20$ bills = " << billsTwenty;
cout << "\nNumber of 10$ bills = " << billsTen;
cout << "\nNumber of 5$ bills = " << billsFive;
cout << "\nNumber of Toonies = " << coinToonie;
cout << "\nNumber of Loonies = " << coinLoonie << endl << endl;
}
cout << endl;
return 0;
}
int cash()
{
}
答案 0 :(得分:2)
基本上有两种方法可以返回多个值。您要么返回struct
或class
作为返回值,要么传入引用值或指针,该函数设置引用/指向的值。
所以如果你必须将金额分成10s和1s:
struct Change {
int Tens;
int Ones;
};
Change cash(int amount) {
Change result;
result.Tens = amount / 10;
result.Ones = amount % 10;
return result;
}
Change broken = break(15);
// Refer to broken.Tens and broken.Ones.
可替换地:
void cash(int amount, int& tens, int& ones) {
tens = amount/10;
ones = amount%10;
}
int tens;
int ones;
cash(15, tens, ones);
在你的应用程序中,我会使用struct - 一个带有七个输出参数的函数有太多的参数。
答案 1 :(得分:0)
要回答您的问题,您无法从C ++中的函数返回多个值。相反,您可以返回包含或引用多个内容的结构或其他对象。例如:
#include <iostream>
struct Foo {
int x;
int y;
};
Foo doSomething() {
Foo f;
f.x = 10;
f.y = 20;
return f;
}
int main()
{
Foo f = doSomething();
std::cout << f.x << std::endl;
std::cout << f.y << std::endl;
}
基于上面的其余代码,我认为可以更好地调用多个函数(getBillsHundred()
等),或者每个函数使用不同的参数(getBillsBySize()
)不同的尺寸。每个函数都只返回一个值。
答案 2 :(得分:0)
您可以考虑使用地图。
std::map<string, int> cash(int dollarAmount) {
std::map<string, int> ret;
ret['hundred'] = dollarAmount / 100;
// stuff similar
return ret;
}