《C++快速入门》课后习题
利用重载函数的方法设计一个程序,改程序通过函数”calc()”进行计算并返回显示结果。当传入一个参数时,计算该参数的平方值;
当传入两个参数时,计算两个参数的积;
当传入三个参数时,计算三个参数的和。
#include <iostream>
#include<math.h>
using namespace std;
double calc(double a);
double calc(double a,double b);
double calc(double a,double b,double c);
int main()
{
int a,b,c;
cout<<"请输入三个实数:"<<endl;
cout<<"a=";
cin>>a;
cout<<"b=";
cin>>b;
cout<<"c=";
cin>>c;
cout<<"a^2="<<calc(a)<<endl
<<"a*b="<<calc(a,b)<<endl
<<"a+b+c="<<calc(a,b,c)<<endl;
}
double calc(double a)
{
return pow(a,2);
}
double calc(double a,double b)
{
return a*b;
}
double calc(double a,double b,double c)
{
return a+b+c;
} C++ Filecopy.cpp
#include <iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
string infile,outfile;
cout<<"输出格式:复制文件名称 新文件名称"<<endl;
getline(cin,infile,'\n');
getline(cin,outfile,'\n');
ifstream imread(infile,ios::in);
ofstream imwrite(outfile, ios::out);
if(imread==NULL)
cout<<"打开文件失败!";
char i;
while(imread>>i)
imwrite<<i;
cout<<"成功复制!";
imread.close();
imwrite.close();
} 定义一个数组容纳10个整数,这些整数来自用户输入。我们将计算这些值的累加和、平均值并输出。#include <iostream>
#include<math.h>
using namespace std;
#define ITEM 5
int main()
{
int a;
cout<<"请输入"<<ITEM<<"个整型数据:"<<endl;
int i;
for(i=0;i<ITEM;i++)
{
cout<<"请输入第"<<i+1<<"个数据:";
while(!(cin>>a))
{
cin.clear();
cin.ignore(100,'\n');
cout<<"请输入一个合法的值";
}
}
int total=0;
for(i=0;i<ITEM;i++)
total+=a;
cout<<"总和是:"<<total<<endl;
cout<<"平均值是:"<<(float)total/ITEM<<endl;
return 0;
} 将用户输入的字符串打印出来#include <iostream>
#include<string>
using namespace std;
int main()
{
string str;
cout<<"请随便输入一个字符串:";
getline(cin,str);
cout<<str<<endl;
return 0;
} double calc(double number1);
double calc(double number1,double number2);//对函数重载
double calc(double number1,double number2,double number3);//对函数重载
int main()
{
double NumberIn1,NumberIn2,NumberIn3,Vule;
std::cout<<"请输入1个数字,并按回车结束"<<"\n\n";
std::cin>>NumberIn1;
std::cin.ignore(100,'\n');
std::cout<<"\n\n";
Vule=calc(NumberIn1);
std::cout<<"该参数的平方值="<<Vule<<"\n\n";
std::cout<<"请输入2个数字,并按回车结束"<<"\n\n";
std::cin>>NumberIn1>>NumberIn2;
std::cin.ignore(100,'\n');
std::cout<<"\n\n";
Vule=calc(NumberIn1,NumberIn2);
std::cout<<"两个参数的积="<<Vule<<"\n\n";
std::cout<<"请输入3个数字,并按回车结束"<<"\n\n";
std::cin>>NumberIn1>>NumberIn2>>NumberIn3;
std::cin.ignore(100,'\n');
std::cout<<"\n\n";
Vule=calc(NumberIn1,NumberIn2,NumberIn3);
std::cout<<"三个参数的和="<<Vule<<"\n\n";
return 0;
}
double calc(double number1)
{
return number1*number1;
}
double calc(double number1,double number2)//对函数重载
{
return number1*number2;
}
double calc(double number1,double number2,double number3)//对函数重载
{
return number1+number2+number3;
}
页:
[1]