C++浮点数组初始化

Ada*_*tan 19 c++ arrays floating-point initialization

可能重复:
C和C++:自动结构的部分初始化

在阅读Code Complete时,我遇到了一个C++数组初始化示例:

float studentGrades[ MAX_STUDENTS ] = { 0.0 };
Run Code Online (Sandbox Code Playgroud)

我不知道C++可以初始化整个数组,所以我测试了它:

#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;
}
Run Code Online (Sandbox Code Playgroud)

该计划给出了预期的结果:

0 0
1 0
2 0
3 0
Run Code Online (Sandbox Code Playgroud)

但是,将初始化值更改0.0为,例如9.9:

float studentGrades[ MAX_STUDENTS ] = { 9.9 };
Run Code Online (Sandbox Code Playgroud)

给出了有趣的结果:

0 9.9
1 0
2 0
3 0
Run Code Online (Sandbox Code Playgroud)

初始化声明是否只设置数组中的第一个元素?

Ed *_* S. 29

如果你使用除空括号之外的任何东西,那么你只需将前N个位置初始化为该值,所有其他位置初始化为0.在这种情况下,N是传递给初始化列表的参数数量,即

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
Run Code Online (Sandbox Code Playgroud)


Mar*_*tos 5

不,它将所有未明确设置为默认初始化值的成员/元素设置为数字类型为零.