gpt4 book ai didi

c - scanf 不断取值(输入)

转载 作者:太空宇宙 更新时间:2023-11-04 07:45:25 25 4
gpt4 key购买 nike

我有一个家庭作业问题,我必须输入一个数组,然后从中取出所有不同的元素。

为此,我创建了一个新的子数组,其中将存储所有不同的值,但是在输入期间 scanf 没有按预期取值吗?

这是我的代码:-

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

int main()
{
int number; // Variable name "number" which will specify the size of dynamically allocated array.

printf("Enter the size of your array\n");
scanf("%d",&number);

int *array;
array = (int*)calloc(number, sizeof(int)); // Dynamically allocated memory.

int i,j=0; // Counter variables for loop.

printf("Enter the elements of arrays\n");

for(i = 0; i < number; i++)
{
scanf("%d",(array + i)); // Code is asking for endless numbers and is not outputting the desired result. THIS IS THE PROBLEM SECTION.
}


for(i = 0; i < number; i++)
{
for( j = i + 1 ; j < number; j++)
{
if( *(array + i ) == *(array + j))
{
*(array + j) = 0; // My way of removing those numbers which are the repeated. (Assigning them value of zero).
}
}
}

i=0;j=0;

int sub_number = 0;

while(i < number)
{
if(*(array + i) != 0)
{
sub_number++; // Variable name "sub_number" which will specify the size of dynamically allocated array "sub_array".
}
}

int *sub_array;
sub_array = (int*)calloc(sub_number,sizeof(int));

for(i = 0;i < sub_number;i++)
{
printf("%d\n",*(sub_array + i)); // Desired array which only contains distinct and unique variables.
}
return 0;
}

编辑:- 我错过了一个循环,我忘记填充 sub_array 循环。这是代码:-

for(i = 0;i < number ;i++) //New code inserted.
{
if( *(array + i ) != 0)
{
*(sub_array + j) = * (array + i );
j++;
}
}

无论如何,我的程序仍然无法运行。

最佳答案

在您的代码的以下部分:

 while(i < number)
{
if(*(array + i) != 0)
{
sub_number++; // Variable name "sub_number" which will specify the size of dynamically allocated array "sub_array".
}
}

你没有递增 i。您错过了 i++;。您的 scanf 周期是正确的。

关于c - scanf 不断取值(输入),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57557661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com