gpt4 book ai didi

c++ - 如果我们声明一个由四个元素组成的数组,这些元素可以存储值吗?

转载 作者:行者123 更新时间:2023-11-30 21:18:47 26 4
gpt4 key购买 nike

在 C++ 中,如果我们声明一个包含四个元素的数组,这些元素可以存储值吗?我的意思是,如果我们声明以下数组:

#include <iostream>
int main()
{
int a[4];
double res;
double avg;
avg = res = 0.0;
for(int i=0; i<4; i++)
{
cout<<"Please enter age ";
cin>> a[i];
}

for(int i=0; i<4; i++)
{
cout<< "You have entered these ages " <<a[i];
cout<<endl;
res += a[i];
}

avg = res/4;
cout<< "Total is "<<res <<endl;
cout<< "Avg is "<<avg;
}

上面的程序是一个带有整数(数字)数组的程序,而在字符数组中我们可以为字符数组的元素分配任意值吗?

最佳答案

是的。

数组是相同类型和编号值的占位符。的位置在数组声明期间被保留。

int a[3];

表示可以存储3个int。可通过 a[0]a[1]a[2] 进行访问。

现在,您可以看到循环中存在的问题:

for(int i=1; i<=4; i++)
{
cout<<"Please enter age ";
cin>> a[i];
}
  1. a[0] 保持为空
  2. 循环运行 4 次:a[1]、a[2]、a[3]、a[4] 并且最后 2 个索引不保留。

您可以按如下方式更正它:

for(int i=0; i<3; i++)
{
cout<<"Please enter age ";
cin>> a[i];
}

您的其他问题:

while in character array can we assign any value of the character array's elements

不,每个索引只会存储一个字符

char c[3];

将恰好存储 3 个char。如果您尝试使用其他索引,可能会导致未定义的行为,段错误。因为您正在尝试访问未分配给您的进程的内存。

关于c++ - 如果我们声明一个由四个元素组成的数组,这些元素可以存储值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14831114/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com