Write a program that prompts the user for the radius of a sphere and prints its volume [duplicate]

一个人想着一个人 提交于 2019-12-13 08:04:41

问题


Im not getting correct answer with the following code below. Can anyone debug this code? When I input radius = 5, the answer I get is 500.000000 whereas the original answer should be 523.80952. Can anyone please explain what's wrong here?

Sphere volume formula =4/3(π x r^3)

#include <stdio.h>

int main()


    {
    float radius = 0;
    float volume;
    float pie = 0;

    printf("Enter radius");
    scanf("%f", &radius);

    pie = 22 / 7;

    volume = (4*pie*radius*radius*radius)/3;
    printf("the volume is %f", volume);

    return 0;
    }

回答1:


You can also write pie = 3.14 ; instead of pie = 22 / 7 ;

And keep in mind that: (a) Arithmetic operation between two integers always returns an integer. (b) Arithmetic operation between two real numbers always returns a real number. (c) Arithmetic operation between an integer and a real number returns a real number.

So, pie = 22 / 7 will return 500.000000 instead of 523.80952. therefore you can also write pie = 22.0 / 7 or pie = 22 / 7.0 or pie = 22.0 / 7.0. These three will return the original answer.




回答2:


The problem is in the line

 pie = 22 / 7;

here, both the operands of the division being integer constants, this is an integer division and the the result get assigned to float, which is not what you want. You need to force a floating point division by saying

pie = ((float)22) / 7;


来源:https://stackoverflow.com/questions/39818778/write-a-program-that-prompts-the-user-for-the-radius-of-a-sphere-and-prints-its

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!