gpt4 book ai didi

c - 在程序中实现指针

转载 作者:太空宇宙 更新时间:2023-11-04 03:32:18 25 4
gpt4 key购买 nike

我编写了一个程序,要求用户输入美分数并打印出构成该数额的硬币类型。

我正在尝试学习指针,我想在我的程序中包含以下内容:

void coins(int cents, int *quarters, int *dimes, int *nickels, int *pennies);

如果有人能教我在我的程序中实现它,我将不胜感激

#include 
#define QUARTER 25
#define DIME 10
#define NICKEL 5
#define PENNY 1

int main()
{
//initialize variables and read input
int cents, pennies, quarters, dimes, nickels;
pennies = quarters = dimes = nickels =0;
printf("Enter the number of cents:\n");
scanf("%d", ¢s);

//check the range of the input amount
if(cents< 0 || cents > 10000)
printf("Invalid amount %d,\nAmount must be between 0 and 10000, inclusive\n", cents);
else {
quarters = cents/QUARTER;
dimes = cents%QUARTER/DIME;
nickels = cents%QUARTER%DIME/NICKEL;
pennies = cents%QUARTER%DIME%NICKEL;

printf("Quarters: %d\n", quarters);
printf("Dimes: %d\n", dimes);
printf("Nickels: %d\n", nickels);
printf("Pennies: %d\n", pennies);
}
return 0;
}

最佳答案

只需包含一些修正

#include <stdio.h>
#define QUARTER 25
#define DIME 10
#define NICKEL 5
#define PENNY 1

void coins(int cents, int *quarters, int *dimes, int *nickels, int *pennies);

int main(void)
{
//initialize variables and read input
int cents, pennies, quarters, dimes, nickels;
pennies = quarters = dimes = nickels =0;
printf("Enter the number of cents:\n");
scanf("%d", &cents);

//check the range of the input amount
if(cents< 0 || cents > 10000)
printf("Invalid amount %d,\nAmount must be between 0 and 10000, inclusive\n", cents);
else {
quarters = cents/QUARTER;
dimes = cents%QUARTER/DIME;
nickels = cents%QUARTER%DIME/NICKEL;
pennies = cents%QUARTER%DIME%NICKEL;

printf("Quarters: %d\n", quarters);
printf("Dimes: %d\n", dimes);
printf("Nickels: %d\n", nickels);
printf("Pennies: %d\n", pennies);
}
return 0;
}

或者利用它

#include <stdio.h>
#define QUARTER 25
#define DIME 10
#define NICKEL 5
#define PENNY 1

void coins(int cents, int *quarters, int *dimes, int *nickels, int *pennies);

int main(void)
{
//initialize variables and read input
int cents, pennies, quarters, dimes, nickels;
pennies = quarters = dimes = nickels =0;
printf("Enter the number of cents:\n");
scanf("%d", &cents);

//check the range of the input amount
if(cents< 0 || cents > 10000)
printf("Invalid amount %d,\nAmount must be between 0 and 10000, inclusive\n", cents);
else {
coins(cents, &quarters, &dimes, &nickels, &pennies);

printf("Quarters: %d\n", quarters);
printf("Dimes: %d\n", dimes);
printf("Nickels: %d\n", nickels);
printf("Pennies: %d\n", pennies);
}
return 0;
}

void coins(int cents, int *quarters, int *dimes, int *nickels, int *pennies)
{
*quarters = cents/QUARTER;
*dimes = cents%QUARTER/DIME;
*nickels = cents%QUARTER%DIME/NICKEL;
*pennies = cents%QUARTER%DIME%NICKEL;
}

关于c - 在程序中实现指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35374298/

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