c++ - 为什么我的代码不输出(仅)数字?

标签 c++ function output

代码练习提示:编写一个程序,告诉从 1 美分到 99 美分的任意数量的找零都应该给什么硬币。使用面额为 25 美分(25 美分)、10 美分(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 << ", ";
}

最佳答案

您正在输出指针的值,而不是所指向对象的值。

简单的解决方法是首先取消对指针的引用:

cout << "You entered " << *change << endl;
//                        ^

cout << *num << " " << coin_name << ", ";
//      ^

但是,我建议根本不要对此类事情使用指针。对于内置类型,您应该在想要更新变量时获取引用,否则应获取值。

就我个人而言,我也不会从函数内部更新这些变量,我会执行必要的输入或计算并返回要分配的值。

关于c++ - 为什么我的代码不输出(仅)数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33032567/

相关文章:

c++ - 在堆栈与堆中没有构造函数的结构/类的初始化

c++ - C++11编译器的构造函数继承产生错误

c - 在带有多个 malloc() 的二维数组的指针上使用 free() 吗?

c - 使用 C 中的指针将二维数组中的行传递给函数

javascript - 重复函数,同时递增 [i]

c - 为什么对于长度为 k 的字符串需要 char[k + 1] 而不是 char[k] ?

python-3.x - 在第一次写入时覆盖文本文件,然后附加到它 - Python

java - 如果用户使用键盘输入错误,如何再次调用该类

c++ - 如何检查模板模板参数类型的唯一性?

c++ - 标记字符串并构建 multimap