练习提示代码:编写一个程序,告诉你给出的任何金额从1美分到99美分的硬币。使用25美分(四分之一),10美分(一分钱)和1美分(便士)的硬币面额。不要使用镍和半美元硬币。您的程序将使用以下功能(以及其他功能): void compute_coins(int coin_value,int& num,int& amount_left);
#include <iostream>
#include <string>
using namespace std;
void prompt(int *amount_left);
void remaining_change(int *amount_left, int coin_value);
void compute_coins(int coin_value, int *num, int *amount_left);
void output(string coin_name, int *num);
int main() {
int change = 0, num = 0, amount_left = 0;
const int quarter = 25, dime = 10, penny = 1;
string q = "quarter(s)", d = "dime(s)", p = "penny(s)";
prompt(&change);
compute_coins(quarter, &num, &amount_left);
remaining_change(&amount_left, quarter);
output(q, &num);
compute_coins(dime, &num, &amount_left);
remaining_change(&amount_left, dime);
output(d, &num);
compute_coins(penny, &num, &amount_left);
output(p, &num);
}
void prompt(int *change)
{
cout << "How much change is there? ";
cin >> *change;
cout << "You entered " << change << endl;
cout << "That is equal to: ";
}
void remaining_change(int *amount_left, int coin_value)
{
*amount_left = (*amount_left % coin_value);
}
void compute_coins(int coin_value, int *num, int *amount_left)
{
*num = *amount_left / coin_value;
}
void output(string coin_name,int *num)
{
cout << num << " " << coin_name << ", ";
}
答案 0 :(得分:1)
您正在输出指针的值,而不是指向的对象的值。
简单的解决方法是首先取消引用指针:
cout << "You entered " << *change << endl;
// ^
cout << *num << " " << coin_name << ", ";
// ^
但是,我建议不要使用指针来完成这样的事情。对于内置类型,您应该在想要更新变量时使用引用,否则应该使用值。
我个人也不会从函数内部更新这些变量,我会执行必要的输入或计算并返回一个要分配的值。