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

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

2012-02-17 12:21 357 查看
静态建立数组:int a[20];

动态建立数组:

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

错误方法:

int input;

cin>>input;

int a[input];

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

int input;

cin>>input;

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

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

菱形数组:

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

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

#include<iostream>
using namespace std;
int main(){
cout<<"Hello C++ world!"<<endl;    cout<<endl;
int len;
cout<<"Please imput a integer Nom."<<endl;
cin>>len;
int *i=new int[len];//动态简历数组
for(int j=0;j<len;j++){i[j]=j;}
int mid=len/2;
cout<<"the length is"<<len<<endl;
cout<<"the middle is"<<mid<<endl;
cout<<endl<<"the matrix is:"<<endl;
for(int k=0;k<len;k++){
int a;
if(k<mid){
a=mid-k;//输出空格从多变到少:常量-增变量
while(a--)cout<<"";
a=k+1;//输出数据从少变到多:增变量
while(a--){
if(i[k]<10)cout<<"0"<<i[k]<<"";//小于10的数,输出时在数字前补0
else cout<<i[k]<<"";
}
cout<<endl;
}
if(k>mid){
a=k-mid+1;//输出空格从少变到多:增变量-常量
while(a--)cout<<"";
a=len-k;//输出数据从多变到少:常量-增变量
while(a--){
if(i[k]<10)cout<<"0"<<i[k]<<"";//小于10的数,输出时在数字前补0
else cout<<i[k]<<"";
}
cout<<endl;
}
}
cout<<endl;
return main();
}


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

该方法的普遍算法:

#include <iostream>
#include <cmath>
int main() {
const int row = 6; // 5行,对于行对称的,使用绝对值来做比较好
const int max = row / 2 + 1;
for (int i = -max + 1; i < max; ++i) {
for (int j = 0; j < abs(i); ++j, std::cout << " ");
for (int j = 0; j < (max - abs(i)) * 2 - 1; ++j, std::cout << "*");
std::cout << std::endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: