您的位置:首页 > 编程语言 > C语言/C++

C++ Primer Plus (第6版)编程练习 代码-----第五章

2014-11-19 11:17 591 查看
这些都是我在学习中所做的练习,难免有不足的地方,欢迎大家交流指教!

1.针对于书本要求的输入两个数字,并计算之间所有整数和的大小,我做了一定的改动,可以任意输入两个数字!

#include "stdafx.h"
#include<iostream>
using namespace std;
int main()
{
int i,j;
int min,max;
cout<<"请输入第一个数字: ";
cin>>i;
cout<<"请输入第二个数字: ";
cin>>j;
if (i<j)
{
i=min;j=max;
}
else
if (i>j)
{
max=i;min=j;
}
else
{
cout<<"数字相等,请重新输入!";
}
int sum=0;
for(int k=min;k<=max;k++)
sum+=k;
cout<<min<<"与"<<max<<"之间的整数和为: "<<sum;
system("pause");
return 0;
}

2.

int main()
{
array<long double,101> mul;
mul[0]=mul[1]=1;
for (int i=2;i<101;i++)
mul[i]=i*mul[i-1];
for (int i=0;i<101;i++)
cout<<i<<"! = "<<mul[i]<<endl;

system("pause");
return 0;
}


3.

int main()
{ int in;
int sum =0;

cout<<"请输入数字(输入0程序结束):";
cin>>in;

while(in!=0)
{ sum+=in;

cout<<"所有数字的和为: "<<sum<<endl;
cout<<"请输入数字(输入0程序结束):";
cin>>in;
}
return 0;
}

4.

  double da=100;
double cl=100;
int i;
for(i=0;da>=cl;i++)
{
da += 10;
cl *=1.05 ;
}

cout<<i<<"年后Cleo的投资价值为:"<<cl<<endl;
cout<<"Daphne的投资价值为: " <<da;

5. 这个指针的部分不太懂,所以直接用的char,而且月份显示到9月的时候,10,11,12 只显示了0,1,2,不知道什么原因

int month[12];
char m[12]={'1','2','3','4','5','6','7','8','9','10','11','12'};
int ch;
int year=0;
for (int i=0;i<12;i++)
{
cout<<"请输入"<<m[i]<<" 月的图书销售量:";
cin>>ch;
month[i]=ch;
year +=ch;
}
cout<<"一年的销售总量为: "<<year;

6.

int sum[3][12];
int year=0;
int mout =0;
int ch;
for(int i=0;i<3;i++)

{ for(int j=0;j<12;j++)
{cout<<"请输入第"<<i+1<<"年,第 "<<j+1<<" 月的图书销售量:";
cin>>ch;
sum[i][j]=ch;
year +=ch;
}
cout<<"第"<<i+1<<"年的销售总量为: "<<year<<endl;
mout+= year;
}
cout<<"3年的销售总量为: "<<mout;

5.7

struct car
{
string maker;
int pdate;
};

int num;

cout<<"How many cars do you wish to catalog? ";
cin>>num;
cin.get();
car * ps=new car[num];
for (int i=0;i<num;i++)
{

cout<<"Car #"<<i+1<<endl;
cout<<"Please enter the maker : ";
getline(cin,(ps+i)->maker);
cout<<"Please enter the year made: ";

cin>>(ps+i)->pdate;
cin.get();
}
cout<<"Here is your collection : "<<endl;
for (int i = 0; i < num; i++)
{
cout << (ps+i)->pdate << " : " << (ps+i)->maker << endl;
}

system("pause");
return 0;

5.8 

cout<<"Enter words (to stop, type the word done)"<<endl;
char ch;
char word[20];
cin>>ch;
int count =0;
int i=0;
while(strcmp(word,"done")!=0)
{
cin.get(ch);
if(ch==' ')
{
word[i]='\0';
count++;
i=0;
}
else
{
word[i]=ch;
word[i+1]='\0';
i++;
}
}

cout<<"you entered a total of "<<count<<" words.\n";
cin.get();


5.9

cout<<"Enter words (to stop, type the word done)"<<endl;
string str;

int count = 0;

do
{
cin>>str;
count++;

}
while(str!="done");
cout<<"you entered a total of "<<count-1<<" words.\n";


5.10

void star(int);
void point(int);
int main {
int iputnum;
cout<<"请输入一个数字:";
cin>>iputnum;

for(int i =1;i<=iputnum;i++)
{

point(iputnum-i);
star( i);
cout<<endl;
}
}
void star(int j)
{ for (int i=1;i<=j;i++)
cout<<"*";
}
void point(int k)
{
for (int i=1;i<=k;i++)
cout<<".";
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息