为什么我的 C 代码计算错误

Why is my C Code miscalculating

我正在尝试编写一个公式来计算用户输入半径的球体的体积。公式为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", &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 ).

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

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;
}