第七章1-3题

来源:互联网 发布:smtp 端口 编辑:程序博客网 时间:2024/06/05 17:13
第一题

#include<iostream>
double avg(double x , double y);
int main()
{
using namespace std;
int x = 0;
int y = 0;
while(1)
{
cout<<"请输入第一个数:";
cin>>x;
if(!cin)
break;
cout<<"请输入第二个数:";
cin>>y;
if(!cin)
break; //首先确保输入的是double
if(x ==0 or y ==0)
break; //然后确保输入的2个数都不为0
cout<<"调和平均数:"<<avg(x,y)<<endl;
}
cout<<"程序结束";
return 0;
}
double avg(double x , double y)
{
return (2*x*y)/(x+y);
}




第二题

#include<iostream>
int fillArray(double golf[] , int limit);
void showArray(const double golf[] , int limit);
void avgArray(const double golf[] , int limit);
const int MAX = 10;
using namespace std;
int main()
{
int SIZE = 0;
double golf[MAX];
SIZE = fillArray(golf,MAX);
showArray(golf,SIZE);
avgArray(golf,SIZE);
return 0;
}
int fillArray(double golf[] , int limit)
{
double achievement = 0;
int size = 0;
golf[0] = 0; //先把数组的第一个数填充位0,如果手动输入的时候第一个数字输入非法可以避免段错误
for(int i = 0 ; i < limit ; ++i)
{
cout<<"请输入第"<<i+1<<"个成绩";
cin>>achievement;
if(!cin)
{
cout<<"输入结束\n";
break;
}
if(achievement < 0 or achievement > 100) //不会高尔夫,假设高尔夫的成绩位0-100直接的double..
{
cout<<"输入结束\n";
break;
}
golf[i] = achievement;
++size;
}
return size;
}
void showArray(const double golf[] , int limit)
{
if(limit == 0)
cout<<"无效的成绩.\n";
for(int i = 0 ; i < limit ; ++i)
cout<<"第"<<i+1<<"个高尔夫成绩为"<<golf[i]<<endl;
}
void avgArray(const double golf[] , int limit)
{
double sue = 0;
for(int i = 0 ; i < limit ; ++i)
sue = sue + golf[i];
if(limit != 0)
sue = sue/limit;
cout<<"高尔夫的平均成绩为"<<sue;
}




第三题

#include<iostream>
using namespace std;
struct box
{
char maker[40];
float height;
float width;
float lenght;
float volume;
};
void showBox(box myBox);
void countVolume(box* myBox);
int main()
{
box boxes = {"Volume",10.1,20.2,30.3,0};
cout<<"立方体数据:\n";
showBox(boxes);
countVolume(&boxes);
cout<<"立方体数据已经更改:\n";
showBox(boxes);
return 0;
}
void showBox(box myBox)
{
cout<<"名称:"<<myBox.maker<<endl;
cout<<"高度:"<<myBox.height<<endl;
cout<<"宽度:"<<myBox.width<<endl;
cout<<"长度:"<<myBox.lenght<<endl;
cout<<"体积:"<<myBox.volume<<endl;
}
void countVolume(box* myBox)
{
myBox->volume = (myBox->height) * (myBox->width) * (myBox->lenght);
}

0 0
原创粉丝点击