accelerated c++ 2章 习题

来源:互联网 发布:男生发型 知乎 编辑:程序博客网 时间:2024/05/01 04:27

2-0:

#include<iostream>
#include<string>

using std::cout;
using std::cin;
using std::endl;
using std::string;


int main(){
 

 cout << "Please enter your first name: ";

 string  name;
 cin >> name;

 const string greeting = "Hello" + name + "!" ;

 

 int pad = 1;
 
 const int rows = pad*2 + 3;

 const string::size_type cols = greeting.size() + pad*2 + 2;
 cout << endl;


 for( string::size_type i = 0; i != rows; i++ ){
  
  string::size_type c = 0;
  while( c != cols ){

   if( i == pad+1 && c == pad+1 ){
    cout << greeting ;
    c = c+greeting.size();
   }

   if( i == 0 || c == 0 || c == cols - 1 || i == rows-1)
    cout << "*";
    else cout << " ";
   if ( c == cols -1 )
    cout << endl ;
   c++;
  }
 }

 

2-1: 将 pad = 1 改为 pad = 0;

 

2-2: 可以修改rows或者cols实现

 

2-3:pad 由用户输入

 

2-4:定义里添加个const string space(greeting.size()+2,' ');

while里加个if( i == 1 || i == rows - 2)
   {cout << "*" << space << "*";
   c = cols - 1;
   }

 

2-5 : (1)

int x =5;
 for( int i = 0 ; i != x; i++ ){
  int j = 0;
  while (j !=x ){
  
   cout << "*";
  
  
   j++;
  
  }
 cout << endl;

 }

 

(2) :

int x =5,y=8; 
 for( int i = 0 ; i != x; i++ ){
  int j = 0;
  while (j !=y ){
  
   cout << "*";
  
  
   j++;
  
  }
 cout << endl;

 }

 

(3) :

 int x =3;
 
 for(  ; x >= 0 ; x-- ){
  int j = 0;
  while (j !=x ){
  
   cout << " ";
  
  
   j++;
  
  }
  int i = 2*(4-x)-1;
  while(i>0){
   cout << "*";
   i--;
   
  }
 cout << endl;

 }

 

2-6:

输出1到10;

 

2-7:

 int i = 10;
 while ( i >= -5){
  cout << i <<" ";
 i--;

 }

 

2-8:

 int i = 1,sum = 1;
 while( i <10 ){
  sum *= i;
  i++;
 }
 cout << sum;

 

2-9:

 cout << "Please enter two numbers" ;
 int i,j;
 cin >> i >>j;

 if( i != j)
  cout << (i>j?i:j) <<endl;
 else cout << "eq" << endl;

 

2-10:

{}作用欲内的 using声明只在该{}内有效

 

原创粉丝点击