首页 文章

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

提问于
浏览
0

代码的运动提示:编写一个程序,告诉你给出的任何金额从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 << ", ";
}

2 回答

  • 1

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

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

    cout << "You entered " << *change << endl;
    //                        ^
    
    cout << *num << " " << coin_name << ", ";
    //      ^
    

    但是,我建议不要使用指针来完成这样的事情 . 对于内置类型,您应该在想要更新变量时使用引用,否则应该使用值 .

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

  • 1

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

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

    至:

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

    但更好的是,您可以使用引用而不是指针:

    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 - 指针方法更“老skool”C风格的编程 .

    同样适用于打印指针本身的其他地方,例如: num .

相关问题