C 编程 : run a program through a loop?

标签 c loops

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

#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/

相关文章:

c - sscanf 读入了错误的值

Objective-C 循环逻辑

ios - 如何在 objective-c 中的数组上执行 "select"?

wordpress - 使用Varnish + Nginx(HTTPS)时的重定向循环

检查标准输入缓冲区是否为空

C Buffer 中的控制字符

python - 使用循环将对象添加到列表(python)

php - 是否可以在所需循环之外创建数据库调用?

c - C中的嵌套结构

c - 数组的指针算术