0

我最近开始学习 C,想知道是否有一种方法可以声明一些整数,并使用用户给出的值。例如,用户输入 3。我想创建 3 个整数,a例如bc。如果用户输入 5,我想创建a, b, c, d, e.

有什么办法吗?

4

3 回答 3

1

您想要创建一个数组,因为您不能声明未定义数量的单个变量。由于您是初学者,我会给您一个完整的答案,如果您愿意,您可以编译它:

#include<stdio.h>
#include<stdlib.h>

int main(){
    int* arr,number,i;
    printf("Give number value: ");
    scanf("%d",&number);
    arr = malloc(sizeof(*arr) * number); // after the comment, it safeguards the code
    for(i=0;i<number;i++){
        printf("%d ",i);
    }
    return 0;
}

arr 是一个指针变量,您可以将它用作一个数组,其大小为 int * 您想要的变量数。

于 2013-04-13T17:20:11.340 回答
0

你需要的是一个整数数组。当您收到“<code>count”值时,您需要动态分配“<code>int”类型的“<code>count”项数组。

有关更多详细信息,请查看malloc ()函数: http: //linux.die.net/man/3/malloc

于 2013-04-13T17:10:34.100 回答
0

我会让你轻松搞定。

您可以创建的是一个数组。数组本质上是存储在一个名称中的一系列元素。如果您不确定如何为您的示例制作/使用数组...这里有一个示例。

int main (void){
int i; //counter
int totalIntegers
int arrayVariableName[100]; //array that can store any amount(100 for this case)
                            //of variables inside.
printf("Enter total amount of variables");
    scanf("%d", &totalIntegers); //collect what the user types, pretend you type 5

for(i=0;i<totalIntegers;i++){ //this will loop 5 times from same example.
   printf("enter a number: ");
     scanf("%d",&arrayVariableName[i]); //will store numbers in array 0(which 
                                        // is holding the integer inside a), 
                                        // array 1(holding b), array 2(holding c)       
                                        //array 3(holding d), array 4(holding e).
   }

}

使用数组和 for 循环,您可以设置允许用户多次输入数字的总量。例如,如果您在 5 中键入 7,则可以保存 7 个变量(a、b、c、d、e、f、g)。如果您计划生成超过 100 个整数,请在数组声明中更改它。有一种方法可以将限制设置为您想要的唯一数量,我上面的答案向您展示了如何,请查看以供参考。

要了解更多信息,只需在 youtube 上搜索“c 中的数组教程”。

于 2013-04-13T17:38:12.583 回答