【问题标题】:Cannot figure out why my code is not working [closed]无法弄清楚为什么我的代码不起作用[关闭]
【发布时间】:2016-10-26 18:59:23
【问题描述】:

几天来我一直在试图找出我的代码出了什么问题;我似乎找不到它。如果语句让我很困惑,所以我想我把它们搞砸了,但仍然不确定。我所知道的是,我非常难过,我很想得到我能得到的所有帮助。

#include <stdio.h>

// function  main begins program execution
int main(void)
{
    int numberOfDays = 0;
    float numberOfMiles = 0;
    float milesCharge = 0;
    float milesTotal = 0;
    float total = 0;
    float subtotal = 0;
    float tax = 0;

    do {
        printf("%s", "How many days was car rented?\t");
        scanf("%d", &numberOfDays);
    } while (numberOfDays < 1 );

    do {
        printf("%s", "How many miles were driven?\t");
        scanf("%d", &numberOfMiles);
    } while (numberOfMiles > 1);

    if (numberOfMiles > 1 || numberOfMiles < 200) {
        milesTotal = numberOfMiles * .40;
    } else {
        milesTotal = numberOfMiles * .35;
    }

    subtotal = milesTotal + numberOfDays * 15;
    tax = subtotal * .06;
    total = tax + subtotal; 

    printf("\nSubtotal:\t\t\t$%.2f\n", subtotal);
    printf("Tax Amount:\t\t\t$%.2f\n", tax);
    printf("Total:\t\t\t\t$%.2f\n", total);
    printf("\n");
}

【问题讨论】:

  • 请提供您期望的输入和输出,以及到目前为止您尝试做些什么来调试您的程序?
  • 我不是 C 编码员,但看起来 while (numberOfDays
  • 欢迎来到 StackOverflow!我们很乐意提供帮助 - 但我们需要您告诉我们问题出在哪里,问题出在哪里,以及您希望从该计划中看到什么。不要让投反对票给你,它们只是因为你没有向我们提供我们需要帮助你的东西而发生。 :)
  • 不知道问题出在哪里;但应该发生的是程序应该将天数乘以 15,如果里程数低于 200,则里程数应该乘以 0.40。如果是 200 或更多,则里程然后乘以 0.35。当我这样做时,它似乎跳过了我的 if 语句。
  • @Boo92 如果您无法确定错误的位置,您需要做的第一件事就是开始调试。将打印语句放入您的代码以打印出变量以查看其值,或使用实际调试器查看程序的完整状态。调试是编程的一项关键技能

标签: c


【解决方案1】:

如果numberOfMiles 应该是float 类型,则必须交换以下行

scanf("%d", &numberOfMiles);

通过

scanf("%f", &numberOfMiles);

或者您可以将类型设置为int

--

如果你想避免死循环,交换

} while (numberOfMiles > 1);

通过

} while (numberOfMiles < 1);

顺便说一句。为什么不允许短于一英里的距离?

例如由

} while (numberOfMiles < 0);

要获得更具体的答案,您必须更准确。

【讨论】:

    【解决方案2】:

    使用 gcc 编译程序会出现以下警告:

    t.c: In function ‘main’:
    t.c:21:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘float *’ [-Wformat=]
         scanf("%d", &numberOfMiles);
         ^
    

    问题是,scanf() 将使用用于 int 变量的二进制格式存储在 numberOfMiles 位置输入的数字,但 numberOfMiles 是一个浮点变量。解释为浮点数的整数位模式可能会有非常不同的含义,甚至可能是非法的浮点值。

    将 numberOfMiles 的类型从 float 更改为 int 可以解决此问题。

    您还应该将第二个 while 条件更改为 while (numberOfMiles &lt; 1)

    我希望,这会有所帮助。

    73,马里奥

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多