c++ - 如何使用不同的函数计算三个数字的总和、平均值和乘积

标签 c++ function

我需要创建一个接受 3 个数字并计算总和、平均值和乘积的程序。我只需要使用ma​​in()get_ABC()compute()display() 函数。我做对了,但我没有得到关于我的数学运算的正确输出。

#include<conio.h>
#include<iostream.h>

float get_A(float A)
{
    cout<<"Enter First Number: ";
    cin>>A;
    return(A);
}

float get_B(float B)
{
    cout<<"Enter Second Number: ";
    cin>>B;
    return(B);
}

float get_C(float C)
{
    cout<<"Enter Third Number: ";
    cin>>C;
    return(C);
}

 float compute_sum(float A,float B,float C)
{
 float sum;

 sum = A + B + C;
 return(sum);

}

float compute_ave(float A,float B,float C)
{
    float ave;
    ave = (A + B + C) / 3;
    return (ave);
}

float compute_prod(float A,float B,float C)
{
    float prod;
    prod = A * B * C;
    return(prod);
}

void display(float sum,float ave,float prod)
{
    cout<<"The sum of three numbers is "<<sum<<".\n";
    cout<<"The average of three numbers is "<<ave<<".\n";
    cout<<"The product of three numbers is "<<prod<<".";
}

float main()
{
    float A,B,C;
    float sum;
    float ave;
    float pro;
    clrscr();
    get_A(A);
    get_B(B);
    get_C(C);
    sum = compute_sum(A,B,C);
    ave = compute_ave(A,B,C);
    pro = compute_prod(A,B,C);
    display(sum,ave,pro);
    getch();
    return(0);
}

这是输出。

Enter First Number: 1
Enter Second Number: 2
Enter Third Number: 3
The sum of three numbers is 0.
The average of three numbers is 0.
The product of three numbers is 0.

我真的需要帮助。我的教授在没有教我如何编码的情况下给我这个问题,所以我只提出了基础知识,我真的放弃了并最终来到这里。如果需要,您可以更改、添加或替换代码(使用基本代码),我将不胜感激。

最佳答案

改变这个:

get_A(A);
get_B(B);
get_C(C);

为此:

A = get_A(A);
B = get_B(B);
C = get_C(C);

以便您使用函数的返回值

此外,main() 应该返回一个int,而不是一个float

此外,在声明变量时对其进行初始化,以避免“在此函数中使用未初始化”警告。

关于c++ - 如何使用不同的函数计算三个数字的总和、平均值和乘积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47713898/

相关文章:

c - 为什么 C 不是动态语言?

c++ - Visual Studio 2019 : Pass include paths between chain-referenced projects

c++ - QOpenGLFunctions 的正确用法

c - 使用函数的参数初始化静态变量

algorithm - 在 int 中找到第 n 个 SET 位

javascript - 在 React 中,如何调用另一个组件中的函数?

javascript - 如何打印出保存在 "contacts"数组中的每个对象

c++ - 有条件地删除模板类中的方法

c++ - 什么是 C++ 中可变参数函数的良好类型安全替代方案?

c++ - SFMLtexture 形状像播放器