gpt4 book ai didi

C++ 用常量值填充数组,循环和改变值

转载 作者:行者123 更新时间:2023-11-28 03:37:55 25 4
gpt4 key购买 nike

这是我正在编写的数组的一些基本代码。我需要用 4 填充数组的所有槽位 (14),然后编写一个循环将槽位 6 和 13 替换为 0。我是初学者,还没有学习 vector ,只是基本的编程 Material 。

const int MAX = 14;

int main ()
{

board ();
cout<<endl;

{


int i;
int beadArray[MAX] = {4};

for (i = 0; i < MAX; i++)
{
beadArray[i] = -1;
}

for (i = 0; i < MAX; i++)
{
cout<<i<<"\t";
}
}


cout<<endl;
system("pause");
return 0;
}

最佳答案

#include <iostream>
#include <cstdlib>
using namespace std;

int main(){

//this constant represents the size we want our array to be
//the size of an array must be determined at compile time.
//this means you must specify the size of the array in the code.
const unsigned short MAX(14);

//now we create an array
//we use our MAX value to represent how large we want the array to be
int beadArray[MAX] = {4};

//now our array looks like this:
//+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
//| 4 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
//+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

//but you want each index to be filled with 4.
//lets loop through each index and set it equal to 4.
for (int i = 0; i < MAX; ++i){
beadArray[i] = 4;
}

//now our array looks like this:
//+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
//| 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 |
//+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

//to set slots 6 and 13 equal to 0, it is as simple as this:
beadArray[6] = 0;
beadArray[13] = 0;

//careful though, is that what you wanted?
//it now looks like this:
//+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
//| 4 | 4 | 4 | 4 | 4 | 4 | 0 | 4 | 4 | 4 | 4 | 4 | 4 | 0 |
//+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

//this is because the [index number] starts at zero.

//index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13
// +---+---+---+---+---+---+---+---+---+---+---+---+---+---+
// | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 |
// +---+---+---+---+---+---+---+---+---+---+---+---+---+---+


//print out your array to see it's contents:
for (int i = 0; i < MAX; i++){
cout << beadArray[i] << " ";
}

return EXIT_SUCCESS;
}

关于C++ 用常量值填充数组,循环和改变值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10309137/

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