我是 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/