C++ 浮点数组初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12790198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:37:28  来源:igfitidea点击:

C++ float array initialization

c++arraysfloating-pointinitialization

提问by Adam Matan

Possible Duplicate:
C and C++ : Partial initialization of automatic structure

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

While reading Code Complete, I came across an C++ array initialization example:

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

float studentGrades[ MAX_STUDENTS ] = { 0.0 };

I did not know C++ could initialize the entire array, so I've tested it:

我不知道 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;
}

The program gave the expected results:

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

0 0
1 0
2 0
3 0

But changing the initialization value from 0.0to, say, 9.9:

但是将初始化值从 更改0.0为,例如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?

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

回答by Ed S.

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.,

如果你使用除了空大括号之外的任何东西,那么你只将前 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

回答by Marcelo Cantos

No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.

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