为啥我的 C 代码计算错误

Posted

技术标签:

【中文标题】为啥我的 C 代码计算错误【英文标题】: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 需要一个整数参数,但您传递的是浮点数,这会导致未定义的行为。 【参考方案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;

【讨论】:

以上是关于为啥我的 C 代码计算错误的主要内容,如果未能解决你的问题,请参考以下文章

请解释为啥这个 C 代码给我一个分段错误?

为啥总是在我的代码中显示语法错误?

为啥我的 CUDA 光线追踪器给我这个线程布局的错误代码 700?

如果我包含“-ansi”编译器选项,为啥我的 C++0x 代码无法编译?

我收到“未定义的引用”错误,我不明白为啥(C++ OO)

为啥我在 C 中收到警告“分段错误,核心转储”