C ++浮点数组初始化 [英] C++ float array initialization
问题描述
可能重复:
C和C ++:自动结构的部分初始化
在阅读完整代码时,我遇到了一个C ++数组初始化的例子:
float studentGrades [MAX_STUDENTS] = {0.0};
我不知道C ++可以初始化整个数组,所以我测试了它:
#include< iostream>
使用namespace std;
int main(){
const int MAX_STUDENTS = 4;
float studentGrades [MAX_STUDENTS] = {0.0};
for(int i = 0; i cout<<我 << studentGrades [i]<< \\\
;
}
return 0;
$ / code>
该程序给出了预期的结果:
0 0
1 0
2 0
3 0
$ b $ 但是将初始化值从 0.0
更改为
float studentGrades [MAX_STUDENTS] = {9.9};
给出了有趣的结果:
0 9.9
1 0
2 0
3 0
初始化声明是否只设置数组中的第一个元素?
那么你只能将前N个位置初始化为该值,而其他所有的位置初始化为0.在这种情况下,N是你传递给初始化列表的参数个数,即
float arr1 [10] = {}; //所有的元素都是0
float arr2 [10] = {0}; //所有元素都是0
float arr3 [10] = {1}; //第一个元素是1,其他元素都是0
float arr4 [10] = {1,2}; //第一个元素是1,第二个元素是2,其他元素都是0
Possible Duplicate:
C and C++ : Partial initialization of automatic structure
While reading Code Complete, I came across an C++ array initialization example:
float studentGrades[ MAX_STUDENTS ] = { 0.0 };
I did not know C++ could initialize the entire array, so I've tested it:
#include <iostream>
using namespace std;
int main() {
const int MAX_STUDENTS=4;
float studentGrades[ MAX_STUDENTS ] = { 0.0 };
for (int i=0; i<MAX_STUDENTS; i++) {
cout << i << " " << studentGrades[i] << '\n';
}
return 0;
}
The program gave the expected results:
0 0
1 0
2 0
3 0
But changing the initialization value from 0.0
to, say, 9.9
:
float studentGrades[ MAX_STUDENTS ] = { 9.9 };
Gave the interesting result:
0 9.9
1 0
2 0
3 0
Does the initialization declaration set only the first element in the array?
If you use anything but empty braces then you only initialize the first N positions to that value and all others are initialized to 0. In this case, N is the number of arguments you passed to the initialization list, i.e.,
float arr1[10] = { }; // all elements are 0
float arr2[10] = { 0 }; // all elements are 0
float arr3[10] = { 1 }; // first element is 1, all others are 0
float arr4[10] = { 1, 2 }; // first element is 1, second is 2, all others are 0
这篇关于C ++浮点数组初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!