type[] typename=new type[size];
如int[] a=new int[2];string[] str=new string[5];
实事上我们平常是用int[],string[]...的,此时我们已经创建一个Array数组,只不过我们平常没有这种意识而已.
(1):type数据类型不能缺;且要统一,而不能是如 int[] a=new Array[];
(2):数组的大小size不能缺,否则c#认为是出错的,因为数组是一段固定长度的内存;
(3):右边是一个中括号[],而不是()
看一个简单实例
#include
using namespace std;
int main()
{
int sample[10]; // this reserves 10 integer elements
int t;
// load the array
for(t=0; t<10; ++t) sample[t] = t;
// display the array
for(t=0; t<10; ++t)
cout << "This is sample[" << t << "]: " << sample[t] << "n";
return 0;
}输出
This is sample[0]: 0
This is sample[1]: 1
This is sample[2]: 2
This is sample[3]: 3
This is sample[4]: 4
This is sample[5]: 5
This is sample[6]: 6
This is sample[7]: 7
This is sample[8]: 8
This is sample[9]: 9
求数组平均值
#include
using namespace std;
int main()
{
int i, avg, min_val, max_val;
int nums[10];
nums[0] = 13;
nums[1] = 18;
nums[2] = 75;
nums[3] = 120;
nums[4] = 1321;
nums[5] = 56;
nums[6] = 13124;
nums[7] = 12123;
nums[8] = -19312;
nums[9] = 88123;
// compute the average
avg = 0;
for(i=0; i<10; i++)
avg += nums[i];
avg /= 10;
cout << "Average is " << avg << 'n';
return 0;
}
Average is 9566
查找数据中最大值与最小值
#include
using namespace std;
int main()
{
int i, avg, min_val, max_val;
int nums[10];
nums[0] = 13;
nums[1] = 18;
nums[2] = 75;
nums[3] = 120;
nums[4] = 1321;
nums[5] = 56;
nums[6] = 13124;
nums[7] = 12123;
nums[8] = -19312;
nums[9] = 88123;
// find minimum and maximum values
min_val = max_val = nums[0];
for(i=1; i<10; i++) {
if(nums[i] < min_val) min_val = nums[i];
if(nums[i] > max_val) max_val = nums[i];
}
cout << "Minimum value: " << min_val << 'n';
cout << "Maximum value: " << max_val << 'n';
return 0;
}
Minimum value: -19312
Maximum value: 88123