您的位置:首页 > 编程语言 > PHP开发

多维数组当一维处理,并用数组模拟向量,来计算向量点积

2009-10-21 21:27 381 查看
#include <iostream>
using namespace std;
//------------------把多维数组当成一位来看待。用一个数组元素类型的指针指向第三行元素地址,然后输出
//------------------理论依据: 多维数组实际存储时 是一维的,连续存放的----------------------------
//------------------计算向量点积,用数组来模拟向量,特别注意:指针参数指向的是多维数组
void dotProduct(int *a ,int *b, int & c)
{
//------a,b都是数组(作为三维向量),点积结果是标量,存入标量 c中
c =a[0]*b[0] +a[1]*b[1] +a[2]*b[2];
}

void main()
{
int a[3][4];
int k=0;
for (int i=0; i<3;i++)
for (int j =0; j<4; j++)
{
a[i][j]=k;
k++;
}

cout<<"output the data :"<<endl;
for ( i=0; i<3;i++)
for (int j =0; j<4; j++)
{
cout<<"   "<<a[i][j];
}

cout<<endl;
cout<<"pointer after :"<<endl;

int* p ;
p=a[2];
for (i=0;i<4;i++)
{
cout<<"    "<<p[i];
}
cout<<endl;

//---------------------向量点积,用数组来模拟向量------------------
int c;
dotProduct(a[0],a[1],c);
cout<<"点积结果: "<<c <<endl;

}


 

//----------a[0]是一个指针,指向一个数组中数据。a也是一个指针,但不指向一个数据,而是指向一个指针地址a[]?

因为如此,所以一下代码出现错误:

C:/Documents and Settings/ra/array.cpp(9) : error C2109: subscript requires array or pointer type
C:/Documents and Settings/ra/array.cpp(43) : error C2664: 'dotProduct' : cannot convert parameter 1 from 'int (*)[4]' to 'int *'
        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
Error executing cl.exe.

array.exe - 7 error(s), 0 warning(s)

#include <iostream>
using namespace std;
//------------------把多维数组当成一位来看待。用一个数组元素类型的指针指向第三行元素地址,然后输出
//------------------理论依据: 多维数组实际存储时 是一维的,连续存放的----------------------------
//------------------计算向量点积,用数组来模拟向量,特别注意:指针参数指向的是多维数组
void dotProduct(int *a ,int *b, int & c)
{
//------a,b都是数组(作为三维向量),点积结果是标量,存入标量 c中
c =a[0][0]*b[1][0] +a[0][1]*b[1][1] +a[0][2]*b[1][2];
}

void main()
{
int a[3][4];
int k=0;
for (int i=0; i<3;i++)
for (int j =0; j<4; j++)
{
a[i][j]=k;
k++;
}

cout<<"output the data :"<<endl;
for ( i=0; i<3;i++)
for (int j =0; j<4; j++)
{
cout<<"   "<<a[i][j];
}

cout<<endl;
cout<<"pointer after :"<<endl;

int* p ;
p=a[2];
for (i=0;i<4;i++)
{
cout<<"    "<<p[i];
}
cout<<endl;

//---------------------向量点积,用数组来模拟向量------------------
int c;
dotProduct(&(*a),&(*a),c);
cout<<"点积结果: "<<c <<endl;

}

//----------a[0]是一个指针,指向一个数组中数据。a也是一个指针,但不指向一个数据,而是指向一个指针地址a[]?


 

改成以下形式就可以了,运行一切正常,哈哈

void dotProduct(int a[][4] ,int b[][4], int & c)
{
//------a,b都是数组(作为三维向量),点积结果是标量,存入标量 c中
c =a[0][0]*b[1][0] +a[0][1]*b[1][1] +a[0][2]*b[1][2];
}


甚至以下这种都正常,原因是参数中第一维不起作用

 

void dotProduct(int a[4][4] ,int b[9][4], int & c)
{
//------a,b都是数组(作为三维向量),点积结果是标量,存入标量 c中
c =a[0][0]*b[1][0] +a[0][1]*b[1][1] +a[0][2]*b[1][2];
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c output include 存储 types