gpt4 book ai didi

C 编程 : run a program through a loop?

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

我正在尝试编写一个程序来计算您的零钱并报告总金额。我能够编写函数来计算变化,但我不确定如何让它循环运行。还有一件事是,我希望用户在程序询问他们的名字时按回车键或返回退出,但我也不确定如何。这是我的第一堂编程课,我正在努力变得更好。感谢您的宝贵时间。

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <time.h>

float countChange(int quarters, int dimes, int nickles, int pennies);

int main(void)
{
int a,b,c,d;
char yourname[20];
printf("Your total money is $ %0.2f \n", countChange(12,23,34,45));
printf("What is your name (Return/Enter to quit)?");
scanf("%s", yourname);
printf("\nHow many quarters do you have? \n" );
scanf("%d", &a);
printf("\nHow many dimes do you have? \n" );
scanf("%d", &b);
printf("\nHow many nickles do you have? \n" );
scanf("%d", &c);
printf("\nHow many pennies do you have? \n" );
scanf("%d", &d);
printf("All counted, %s has $ %0.2f\n", yourname, countChange(a,b,c,d));
return 0;
}

float countChange(int quarters, int dimes, int nickles, int pennies)
{
float QuartersTotal, DimesTotal, NicklesTotal, PenniesTotal, total;
QuartersTotal= quarters*0.25;
DimesTotal= dimes*0.10;
NicklesTotal= nickles*0.05;
PenniesTotal= pennies*0.01;
total= QuartersTotal+ DimesTotal+ NicklesTotal+ PenniesTotal;
return total;
}

最佳答案

我建议您应该使用fgets 而不是scanf 来读取任意长度的字符串,这样更安全。 (避免溢出)

while (1)
{
printf("Your total money is $ %0.2f \n", countChange(12, 23, 34, 45));
printf("What is your name (Return/Enter to quit)?");

fgets(yourname, sizeof(yourname), stdin);

if (yourname[0] == '\n')
break;

printf("\nHow many quarters do you have? \n");
scanf("%d", &a);
printf("\nHow many dimes do you have? \n");
scanf("%d", &b);
printf("\nHow many nickles do you have? \n");
scanf("%d", &c);
printf("\nHow many pennies do you have? \n");
scanf("%d", &d);
printf("All counted, %s has $ %0.2f\n", yourname, countChange(a, b, c, d));
getchar();
}

关于C 编程 : run a program through a loop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52937080/

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