【问题标题】:Why is my C Code miscalculating为什么我的 C 代码计算错误
【发布时间】:2017-06-18 07:08:39
【问题描述】:

我正在尝试编写一个公式来计算球体的体积,用户输入半径。公式为V = (4/3)PI r*r*r。无论输入是什么,我都无法弄清楚为什么我的代码只是说音量是 1。这是我正在使用的:

#include <stdio.h>

int main(void) {

    float pi, r, v;

    pi = 3.1416;

    printf("What is the radius?\n");
    scanf("%d", &r);

    v = ((4/3) * pi) * r * r * r;

    printf("Volume of the sphere is: %d\n", v);

    if (v>10)
        printf("Volume is greater than 10");

    return 0;
}

【问题讨论】:

  • scanf("%d", &amp;r); 是错误的。查阅文档。
  • 4/3 计算结果为 1。
  • (4/3) -> (4.0/3.0).
  • 请阅读How to debug small programs。不推荐使用 SO 调试技术。如果你学会自助,你会得到更好的服务。
  • %d in printf 需要一个整数参数,但您传递的是浮点数,这会导致未定义的行为。

标签: c scanf integer-division


【解决方案1】:

在我看来存在多个问题。

首先,

  scanf("%d", &r);

应该是

 scanf("%f", &r);

因为rfloat。将不兼容的类型作为参数传递会导致 undefined behavior。请仔细检查格式说明符和提供的参数类型。

同样适用于

     printf("Volume of the sphere is: %d\n", v);

另外,正如%f 期望float(或double,确切地说,float,无论如何,默认参数提升被提升为double),不是强>%d.

启用附加选项后,编译器可能会警告您不匹配(至少,gcc 可以做到这一点)。启用所有警告,它应该会为您指出问题。

那么,以后

   v = ((4/3) * pi) * r * r * r;

4/3 产生一个整数除法(给出1),所以它不会像你认为的那样做。如果需要,您需要强制执行浮点除法,例如:

v = (pi * 4 / 3) * r * r * r;

(其中float pi 乘以4 得到一个浮点数,当除以3保持 float)。

【讨论】:

  • @StoryTeller 当然,当然,我没有反驳你,只是修改了我的答案,这是一个很好的补充。
  • 谢谢!这完美地解决了它!
  • @SouravGhosh:您还可以补充一点,pi 的值并不准确。
【解决方案2】:

计算球体体积的修改代码。

int main(void) {

    float pi, r, v;

    pi = 3.1416;

    printf("What is the radius?\n");
    scanf("%f", &r); //%d is for integers and %f is for float

    v = ((4.0/3.0) * pi) * r * r * r; // (4/3) typecasts to an integer and results to 1

    printf("Volume of the sphere is: %f\n", v); //%d is for integers and %f is for float

    if (v>10)
        printf("Volume is greater than 10\n");

    return 0;
}

【讨论】:

    猜你喜欢
    • 2019-12-05
    • 1970-01-01
    • 2022-01-16
    • 2020-02-27
    • 2021-06-09
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多