编写一个程序,不断要求用户输入两个数,直到其中的一个为0。对于 每两个数,程序将使用一个函数来计算它们的调和平均数,并将结果返回给main(),而后者将报告结果。调和平均数指的是倒数平均值的倒数,计算公式如下:
调和平均数=2.0 * x * y / (x + y)
#include<iostream> using namespace std; const int a = 2.0; template <typename T> inline T Sum_ADD(T X,T Y){ T sum = (a*X*Y)/(X+Y); return sum; } int main(int argc, char* argv[]){ int a,b; int sum; cout<<"input num_a and num_b: "; while(cin>>a>>b,a*b!=0) //这样判断有一点bug,可以修改一下 { sum+=Sum_ADD(a,b); } cout<<sum<<endl; return 0; }
#include <iostream> using namespace std; double Reciprocal(int a,int b); int main() { int a,b; double sum=0; while(1) { cout<<"a:"; cin>>a; if(a==0) break; cout<<"b:"; cin>>b; if(b==0) break; sum+=Reciprocal(a,b); } cout<<sum<<endl; return 0; } double Reciprocal(int a,int b) { auto reciprocal=2.0*a*b/(a+b); return reciprocal; }