c++ - 球 jar 容积的最终答案无效

标签 c++ c

我创建的这个程序应该基本上使用公式 V=Pi*h^2(3r-h)/3 但我的最终答案并没有相加。

例如:如果我用 1 代替半径,用 2 代替高度,我应该得到 4.18,但通过程序我得到 -1。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double calculatevolume(double);

double main() {
    double radius, height;
    double sum;    //for storing the radius of the reservoir given by the user
    //for storing the calculated volume of the water.

    printf("Please enter the Radius in meters first and then the Height in meters right after:\n"); //Displays the message on the screen

    scanf("%lf",&radius);
    printf("Value of r: %f\n", radius);

    scanf("%lf",&height);
    printf("Value of h: %f\n", height);

    sum = calculatevolume(sum);

    printf("For a reservoir of radius: %.2f m\nAnd a water depth: %.2f m\nThe water volume is: %.2f m^3\n",radius,height,sum);

    system("PAUSE");
}

double calculatevolume(double sum) {
    double radius;
    double height;

    sum = ((((3 * radius) - height)/3) * 3.14 * height * height);

    return sum;
}

最佳答案

尝试这段代码,您应该将高度和半径传递给函数:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double calculatevolume(double,double,double);
double main() {
    double radius, height;
    double sum;    //for storing the radius of the reservoir given by the user
     //for storing the calculated volume of the water.

    printf("Please enter the Radius in meters first and then the Height in meters right after:\n"); //Displays the message on the screen

    scanf("%lf", &radius);
    printf("Value of r: %f\n", radius);


    scanf("%lf", &height);
    printf("Value of h: %f\n", , height);

    sum = calculatevolume(sum,radius,height);

    printf("For a reservoir of radius: %.2f m\nAnd a water depth: %.2f m\nThe water volume is: %.2f m^3\n",radius,height,sum);

    system("PAUSE");
}

double calculatevolume(double sum, double radius, double height) {
    sum = ((((3 * radius) - height)/3) * 3.14 * height * height);
    return sum;
}

你也可以从函数头中删除sum,没有必要传递它

关于c++ - 球 jar 容积的最终答案无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46395440/

相关文章:

c++ - 如何读取然后写回一个宽字符串?

c++ - 微软VS2010编译Qwt

c - 为什么在链表中按排序顺序插入节点时使用双指针?

c - 关闭标准输出后调用 printf 会发生什么?

c++ - 从 QT 中的字符串显示(呈现)HTML

c++ - 指向外围硬件的指针作为模板参数

c++ - 使用 CMake ExternalProject_Add 构建 mongo-cxx-driver

c++ - Make - "Treat warning as error"对于特定文件

c - 将可分配数组从 fortran 传递到 C 并对其进行 malloc

C——基本结构问题