c - scanf 不断取值(输入)
问题描述
我有一个作业问题,我必须输入一个数组,并从中取出所有不同的元素。
为此,我创建了一个新的 sub_array ,其中将存储所有不同的值,但是在输入期间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 循环是正确的。
推荐阅读
- scilab - Scilab 中的 Gauss Seidel 收敛
- kotlin - 新实体的多个条件插入会在 R2DBC 中产生重复条目错误
- javascript - 如何在JS中随机单独播放音频文件
- javascript - 在chartJs中创建堆叠水平条形图的问题
- kotlin - maven-将缺少的工件发布到存储库
- abbyy - Abbyy Flexicapture 中的发票日期提取
- java - 从 mongodb 集合中的数组中获取值
- r - 使用向量作为 grep 模式
- java - 找到至少出现 k 次的最小整数
- linux - ubuntu docker 镜像 18.04 的 Linux 头文件