c - 将数组中的值设置为仅等于 1 或 0

标签 c arrays loops

我是 C 初学者,试图要求用户在数组中输入他们想要的数字数量(最多 10 个),然后输入这些值。然而我的项目说我必须将数组中的值设置为 1(如果有值)或 0(如果没有值)。我也不明白的是我应该找到数组的差异和互补,但是改变值不会也会改变答案吗?

例如:如果用户输入 2 4 5,则数组将类似于 (0, 0, 1, 0, 1, 1, 0, 0, 0, 0)。

这就是我到目前为止所拥有的。

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


int main() {
    int o = 0;
    int p = 0;
    int i = 0;

    printf("Enter the number of elements for set A: ");
    scanf("%d",&o);

    int c[o];

    printf("\nEnter the numbers in set A:\n");
    for(i=0;i<o;i++) {
        scanf("%d",&c[i]);
    }

    printf("\nEnter the number of elements for set B: ");
    scanf("%d",&p);

    int d [p];

    printf("\nEnter the numbers in set B:\n");
    for(i=0;i<p;i++) {
        scanf("%d",&d[i]);
    }
}

最佳答案

你的项目的意思是,当用户输入任何数字时,你必须将该数字对应的数组索引设置为1

例如如果用户输入 1,您的数组应类似于 (0, 1, 0, 0, 0, 0, 0, 0, 0, 0)。由于数组索引是基于 0 的,因此您将第二个元素设置为 1 而不是第一个元素。

编辑:1

您的代码应如下所示:

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

int main()
{
    int o = 0;
    int p = 0;
    int i = 0;
    int input = 0;

    printf("Enter the number of elements for set A: ");
    scanf("%d",&o);
    int c[10];//Edited to correct the size of Array as mentioned by @Jonathan Leffler in the comments
    //To set the initial values to 0
    for(i=0; i<o; i++)
    {
        c[i] = 0;
    }

    //Set the value at the index to 1 when user enters it, as you don't need to store them
    printf("\nEnter the numbers in set A:\n");
    for(i=0; i<o; i++)
    {
        scanf("%d", &input);
        c[input] = 1;
    }

    printf("\nEnter the number of elements for set B: ");
    scanf("%d",&p);
    int d[10];
    //To set the initial values to 0
    for(i=0; i<p; i++)
    {
        d[i] = 0;
    }

    printf("\nEnter the numbers in set B:\n");
    for(i=0; i<p; i++)
    {
        scanf("%d", &input);
        d[input] = 1;
    }
}

关于c - 将数组中的值设置为仅等于 1 或 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46280936/

相关文章:

c++ - 你能解释一下 bool 如何控制循环吗?

c - 在 C.Fork() 中制作自定义 shell

c - 与控制台输出相同内容相比,为什么我的 C 程序的文件输出缺少最后几行?

更改数组元素的代码会更改不同的变量

javascript - 在 JavaScript 中过滤数组的数组以使其变得唯一

c++ - 学习C++,从一本书中寻找关于这个项目的说明

php - 将 PHP 数组中的相同项目分组并进行计数

c - 数组指针的自动类型转换

c++ - 使用特定值初始化可变二维数组

for 循环/数组插入和构造中的 if 语句出现 JavaScript 错误