C语言中如何把数字存到数组里
时间: 2024-04-16 16:28:06 浏览: 108
在C语言中,你可以使用数组来存储数字。首先,你需要声明一个数组,并指定数组的大小。然后,你可以使用循环将数字逐个存储到数组中。
以下是一个示例代码,演示了如何将数字存储到数组中:
```c
#include <stdio.h>
int main() {
int numbers[5]; // 声明一个大小为5的整型数组
printf("请输入五个数字:\n");
// 使用循环从用户输入中依次读取五个数字,并存储到数组中
for (int i = 0; i < 5; i++) {
scanf("%d", &numbers[i]);
}
printf("您输入的数字是:\n");
// 使用循环遍历数组,并打印每个数字
for (int i = 0; i < 5; i++) {
printf("%d\n", numbers[i]);
}
return 0;
}
```
在上面的代码中,我们声明了一个整型数组 `numbers`,大小为5。然后,使用 `scanf` 函数从用户输入中读取五个数字,并使用循环将它们存储到数组中。最后,我们再次使用循环遍历数组,并打印每个数字。
注意:在使用 `scanf` 函数读取用户输入时,要确保输入的类型与数组元素的类型匹配。在上面的示例中,我们假设用户输入的是整数。如果用户输入的是其他类型的数据(如浮点数),则需要相应地修改代码。
相关问题
c语言输入数字存到数组中并输出
您好!以下是将C语言中输入的数字存储到数组中并输出的代码示例:
```c
#include <stdio.h>
int main() {
int nums[10];
int i;
printf("请依次输入10个数字:\n");
for (i=0; i<10; i++) {
scanf("%d", &nums[i]);
}
printf("您输入的数字为:");
for (i=0; i<10; i++) {
printf("%d ", nums[i]);
}
return 0;
}
```
希望对您有帮助!
C语言嗯输入一行字符把其中非数字存到数组中并输出
可以使用C语言的字符数组和循环语句来实现这个功能。具体代码如下:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, j;
printf("请输入一行字符:\n");
fgets(str, 100, stdin);
char non_digits[100];
j = 0;
for (i = 0; str[i] != '\0'; i++) {
if (!isdigit(str[i]) && str[i] != ' ') {
non_digits[j++] = str[i];
}
}
non_digits[j] = '\0';
printf("非数字字符为:%s\n", non_digits);
return 0;
}
```
上述代码中,首先定义了一个长度为100的字符数组`str`,并使用`fgets`函数从标准输入中读取一行字符。接着定义了另外一个长度为100的字符数组`non_digits`,用来存储非数字字符。使用循环语句遍历`str`数组中的每个字符,判断是否为数字或空格。如果不是数字或空格,则将该字符存入`non_digits`数组中。最后输出`non_digits`数组即可。需要注意的是,在`non_digits`数组的末尾加上了一个空字符,以便输出时正确显示。
阅读全文
相关推荐
















