当心数据类型转换发生错误。
尽量使用显式的数据类型转换(让人 们知道发生了什么事),避免让编译器轻悄悄地进行隐式的数据类型转换。
1 #include <iostream> 2 #include <valarray> 3 #include <math.h> 4 5 using namespace std; 6 7 #define ARRAY_SIZE 3 //array size 8 9 //测试valarray容器 10 /* run this program using the console pauser or add your own getch, system("pause") or input loop */ 11 12 int main(int argc, char** argv) { 13 //创建具有3个元素的数组val_array 14 valarray<double> val_array(ARRAY_SIZE); 15 16 //设置数组的值为1, 4, 9 17 for (int i = 0; i < ARRAY_SIZE; i++) 18 val_array[i] = (i+1) * (i+1); 19 20 //显示val_array数组的大小 21 cout << "Size of val_array = " << val_array.size() << endl; 22 23 // 显示val_array数组的值 24 cout << "The values in val_array before calling sqrt() and pow():" << endl; 25 for (int i = 0; i < ARRAY_SIZE; i++) 26 cout << val_array[i] << " "; 27 cout << endl; 28 29 //声明一个rev_valarray数组,其保存对数组val_array的取反 30 valarray<double> rev_valarray(ARRAY_SIZE); 31 for (int i = 0; i < ARRAY_SIZE; i++) 32 rev_valarray[i] = val_array[ARRAY_SIZE - i - 1]; 33 34 //显示rev_valarray数组的大小和元素 35 cout << "Size of rev_valarray = " << rev_valarray.size() << endl; 36 cout << "The values in rev_valarray:" << endl; 37 for (int i = 0; i < ARRAY_SIZE; i++) 38 cout << rev_valarray[i] << " "; 39 cout <<endl; 40 41 // 声明rvalue_array数组,其存放调用sqrt()和pow()函数的返回值 42 valarray<double> rvalue_array; 43 44 //调用sqrt()函数并显示结果 45 rvalue_array = sqrt(val_array); 46 cout << "The result of rvalue_array after calling sqrt():" << endl; 47 for (int i = 0; i < ARRAY_SIZE; i++) 48 cout << rvalue_array[i] << " "; 49 cout <<endl; 50 51 //对val_array数组元素计算幂函数并显示 52 rvalue_array = pow(val_array, rev_valarray); 53 cout << "The result after calling pow(val_array, rev_valarray):" 54 << endl; 55 for (int i = 0; i < ARRAY_SIZE; i++) 56 cout << rvalue_array[i] << " "; 57 cout <<endl; 58 59 //对val_array数组元素计算幂函数,指数均为2.0,并显示 60 rvalue_array = pow(val_array, 2.0); 61 cout << "The result after calling pow(val_array, 2.0):" << endl; 62 for (int i = 0; i < ARRAY_SIZE; i++) 63 cout << rvalue_array[i] << " "; 64 cout <<endl; 65 66 //对2.0进行幂函数运算,指数均为数组val_array的各元素值 67 rvalue_array = pow(2.0, val_array); 68 cout << "The result after calling pow(2.0, val_array):" << endl; 69 for (int i = 0; i < ARRAY_SIZE; i++) 70 cout << rvalue_array[i] << " "; 71 cout <<endl; 72 73 //对val_array和rvalue_array求和 74 cout<<"val_array.sum()="<<val_array.sum()<<endl; 75 cout<<"rvalue_array.sum()="<<rvalue_array.sum()<<endl; 76 77 //求最大值并显示 78 cout<<"val_array.max()="<<val_array.max()<<endl; 79 cout<<"rvalue_array.max()="<<rvalue_array.max()<<endl; 80 return 0; 81 }