gpt4 book ai didi

C 程序无法使用用户创建的函数输出正确的值

转载 作者:行者123 更新时间:2023-11-30 18:55:57 24 4
gpt4 key购买 nike

我尝试编写一个程序,询问用户两个输入,然后计算体积。然而,程序一直给我 0.00000。

#include <stdio.h>
#include <math.h>
#define PI 3.14159


float calvolume(float rad, float h)
{

return (1/3)*PI*pow(rad,2)*h;

}



int main()
{
float radius, height, volume;

printf("Please enter a radius: \n");
scanf("%f",&radius);

printf("Please enter a height: \n");
scanf("%f",&height);

volume = calvolume(radius,height);

printf("The volume is : %f \n",volume);

return 0;
}

最佳答案

 return (1/3)*PI*pow(rad,2)*h;

(1/3) means zero

整数除法为零。做到这一点

 return (1.0f/3.0f)*PI*pow(rad,2.0f)*h;
1.0f to avoid promotion, being probably faster.

更好的是:

 return (0.333333333f)*PI*pow(rad,2.0f)*h;

更好:

 return (0.333333333f)*PI*rad*rad*h;

关于C 程序无法使用用户创建的函数输出正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25982491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com