存储值从一个for循环到一个数组 [英] store value from a for-loop into an array

查看:203
本文介绍了存储值从一个for循环到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个for循环读取值保存到一个数组

 所以char a [];
INT X;
INT Y = 5;的for(int i = 0; INT I = 1000;我++){
   X = X + Y;
   //然后存储/追加x作为字符数组,A ....什么是语法元素?
}


解决方案

通过查看code我假设你正在试图建立一个静态数组,所以我会证明(所以你不必把重点放在像的malloc暂且)概念。然而有几个问题你code,我现在走了过来。

首先阵列声明:

 所以char a [];

对我来说它看起来像你的for循环填充整数数组,所以这个数组应被声明为一个整数,而且你不设置数组的大小,因为你的code的我递增,直到1000你应该只声明整数数组有1000个元素:

  int类型的[1000];

二你的循环:

 的for(int i = 0,INT I = 1000;我++)

你最好只是宣告 I 您的变量的休息,虽然可以在声明它的循环,我个人不建议这样做。你同样在这个循环中声明 I 的两倍。最后,你的病情继续循环(我= 1000 )将立刻中止循环,因为 I 将永远不等于 1000 ,因为你把它设置为 0 。记住一个for循环只有在中间的说法是正确的循环。因此,考虑到这一点,你现在应该有:

  int类型的[1000],I,X,Y = 5;
对于(i = 0; I< 1000;我++)

现在,我们可以使用 = 语句和 i的值来设置每个数组元素为 A

  int类型的[1000],I,X,Y = 5;
对于(i = 0; I< 1000;我++)
{
    X + = Y;
    A [i] = X;
}

就这么简单!

I would like to store values read from a for-loop to an array

char A[];
int x;
int y=5;

for( int i=0; int i =1000; i++) {
   x = x+y;
   // then store/append x as elements of the char array, A.... what is the syntax?
}

解决方案

By looking at your code I am assuming that you are trying to build a static array, so I will demonstrate that (so you don't have to focus on concepts like malloc for the time being). There is however, several problems with your code that I will go over now.

First off your array declaration:

char A[];

to me it looks like your for loop is filling an array of integers, so this array should be declared as an integer, furthermore you are not setting the size of the array, since your code has i increment until it is 1000 you should just declare an integer array with 1000 elements:

int A[1000];

Second your for loop:

for(int i = 0, int i = 1000; i++)

you're better off just declaring i with the rest of your variables, although you can declare it in a for loop I personally wouldn't suggest doing it. Also you declare i twice in this loop. Finally your condition to continue the loop (i = 1000) will abort the loop immediatly since i will never be equal to 1000 since you set it to 0. Remember a for loop only loops while the middle statement is true. So with that in mind you should now have:

int A[1000], i, x, y = 5;
for(i = 0; i < 1000; i++)

And now we can use the = statement and the value of i to set each array element for A:

int A[1000], i, x, y = 5;
for(i = 0; i < 1000; i++)
{
    x += y;
    A[i] = x;
}

it's that simple!

这篇关于存储值从一个for循环到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆