【问题标题】:Why is my code not outputting (just) numbers?为什么我的代码不输出(仅)数字?
【发布时间】:2015-10-09 07:36:41
【问题描述】:

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

【问题讨论】:

  • 这也是它的输出:有多少变化? 54 你输入了 0x7fff6d1cbf08 等于:0x7fff6d1cbf04 Quarter(s), 0x7fff6d1cbf04 dime(s), 0x7fff6d1cbf04 penny(s),
  • 它是输出内存地址,你应该输出指针数据而不是它的内存地址。 cout
  • 我现在得到了输出数据的代码,但它只输出 0。
  • @Al13y 那么你需要查看你的程序逻辑,也许通过调试器运行。一个问题是amount_left 永远不会是0 以外的任何东西。
  • 是的。我想我本来打算用零钱,但是用amount_left写的。我修好了它。我正在尝试通过使 main 中的一组函数成为他们自己的函数来优化它,所以 main 只会调用一条线来表示季度、角钱和便士,但我只是得到越来越多的错误,所以我想现在就离开它。

标签: c++ function output


【解决方案1】:

你输出的是指针的值,而不是指向的对象的值。

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

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

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

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

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

【讨论】:

    【解决方案2】:

    prompt() 中,change 是一个指针,因此为了输出change 指向的值,您需要修改这一行:

    cout << "You entered " << change << endl;
    

    到:

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

    不过,更好的是,您可以使用 reference 而不是指针:

    void prompt(int &change)
    {
        cout << "How much change is there? ";
        cin >> change;
        cout << "You entered " << change << endl;
        cout << "That is equal to: ";
    }
    

    然后您可以将其称为:

    prompt(change);
    

    这更像是惯用的 C++——指针方法更像是“老派”的 C 风格编程。

    打印指针本身的其他地方也是如此,例如num.

    【讨论】:

      猜你喜欢
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-03
      • 2023-03-07
      • 2019-10-07
      • 1970-01-01
      相关资源
      最近更新 更多