C++初学之 1. 数组(菱形矩阵):动态建立数组,算法小结

静态建立数组:int a[20];

动态建立数组:

——————————————————————————————————

错误方法:

int input;

cin>>input;

int a[input];

——————————————————————————————————
 正确方法:

int input;

cin>>input;

 int *a=new int[len];//动态简历数组

——————————————————————————————————

菱形数组:

1. 输入一维数组长度len。

2. 动态建立数组并赋值为该数组的下标数值。

 1 #include<iostream>
2 using namespace std;
3 int main(){
4 cout<<"Hello C++ world!"<<endl; cout<<endl;
5 int len;
6 cout<<"Please imput a integer Nom."<<endl;
7 cin>>len;
8 int *i=new int[len];//动态简历数组
9 for(int j=0;j<len;j++){i[j]=j;}
10 int mid=len/2;
11 cout<<"the length is"<<len<<endl;
12 cout<<"the middle is"<<mid<<endl;
13 cout<<endl<<"the matrix is:"<<endl;
14 for(int k=0;k<len;k++){
15 int a;
16 if(k<mid){
17 a=mid-k;//输出空格从多变到少:常量-增变量
18 while(a--)cout<<"";
19 a=k+1;//输出数据从少变到多:增变量
20 while(a--){
21 if(i[k]<10)cout<<"0"<<i[k]<<"";//小于10的数,输出时在数字前补0
22 else cout<<i[k]<<"";
23 }
24 cout<<endl;
25 }
26 if(k>mid){
27 a=k-mid+1;//输出空格从少变到多:增变量-常量
28 while(a--)cout<<"";
29 a=len-k;//输出数据从多变到少:常量-增变量
30 while(a--){
31 if(i[k]<10)cout<<"0"<<i[k]<<"";//小于10的数,输出时在数字前补0
32 else cout<<i[k]<<"";
33 }
34 cout<<endl;
35 }
36 }
37 cout<<endl;
38 return main();
39 }

本程序纯属新手编写,应该有更简便的编程方法,初学阶段,编出一个小程序,很高兴,下一次学习的目标是:螺旋二位数组

该方法的普遍算法:

 1 #include <iostream>
2 #include <cmath>
3 int main() {
4 const int row = 6; // 5行,对于行对称的,使用绝对值来做比较好
5 const int max = row / 2 + 1;
6 for (int i = -max + 1; i < max; ++i) {
7 for (int j = 0; j < abs(i); ++j, std::cout << " ");
8 for (int j = 0; j < (max - abs(i)) * 2 - 1; ++j, std::cout << "*");
9 std::cout << std::endl;
10 }
11 return 0;
12 }


 

posted @ 2012-02-17 12:21  LeeKing  阅读(636)  评论(0编辑  收藏  举报