gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:19:31 25 4
gpt4 key购买 nike

代码练习提示:编写一个程序,告诉从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com