gpt4 book ai didi

c - 如何查看数组中数字是否具有相同的数字?

转载 作者:行者123 更新时间:2023-11-30 19:29:04 24 4
gpt4 key购买 nike

我有点陷入我的问题之一,不是因为我不知道,而是因为我无法使用更复杂的操作。(函数和多个数组)

所以我需要用 C 语言编写一个程序,要求输入一个数组(最多 100 个元素),然后程序需要按具有相同数字的数字对该矩阵进行排序。

所以我做了我所知道的一切,我用从最小值到最大值的排序算法测试了我的程序,它有效,唯一我不明白的是我应该如何测试循环内的数字是否具有相同的数字? (我无法使用函数。)

所以我知道查找数字是否具有相同数字的方法,但我不知道如何比较它们。这是我需要的示例。

这就是我现在所拥有的,将数字从最小到最大排序。

#include <stdio.h>

int main() {

int matrix[100];
int i,j;
int temp,min;
int elements_number=0;

printf("Enter the values of matrix-max 100 elements-type -1 to end: ");

for(i=0;i<100;i++){
scanf("%d",&matrix[i]);
elements_number++;
if(matrix[i]==-1){
elements_number--;
break;
}
}

for (i=0; i<elements_number; i++) {
min=i;
for (j=i+1; j<elements_number; j++) {
if (matrix[j] < matrix[min])
min = j;
}
temp = matrix[i];
matrix[i] = matrix[min];
matrix[min] = temp;
}

for(i=0;i<elements_number;i++){
if(i!=elements_number-1){
printf("%d,",matrix[i]); }
else printf("%d.",matrix[i]);

}
return 0;
}

我需要这些数字的输出:

INPUT :
1 22 43 444 51 16 7 8888 90 11 -1

OUTPUT:
1,22,444,7,8888,11,43,51,16,90.

1 位整数被视为“具有相同位数的数字”,例如本例中的 7 和 1。

希望对您有所帮助。

最佳答案

处理完数组后,个位数应该都在数组的左侧,其他数字在右侧。在每个部分中,应保留元素的原始顺序。这称为稳定分区。它与排序不同,因为元素仅分为两组。排序意味着数组中任意两个元素之间存在明确的关系。

这可以通过“过滤”数组中的单位数字并将过滤掉的其他数字存储在临时的第二个数组中来完成。然后将第二个数组的内容附加到(现在更短的)第一个数组中。

其工作原理如下:

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

void print(const int *arr, int n)
{
for (int i = 0; i < 10; i++) {
if (i) printf(", ");
printf("%d", arr[i]);
}

puts(".");
}

int is_rep_digit(int n)
{
int q = n % 10;

n /= 10;

while (n) {
if (n % 10 != q) return 0;
n /= 10;
}

return 1;
}

int main()
{
int arr[10] = {1, 22, 43, 444, 51, 16, 7, 8888, 90, 11};
int aux[10]; // auxliary array for numbers with several digits

int i, j, k;

print(arr, 10);

j = 0; // number of single-digit numbers
k = 0; // number of other numbers

for (i = 0; i < 10; i++) {
if (is_rep_digit(arr[i])) {
arr[j++] = arr[i]; // pick single-digit number
} else {
aux[k++] = arr[i]; // copy other numbers to aux
}
}

k = 0;
while (j < 10) { // copy aux to end of array
arr[j++] = aux[k++];
}

print(arr, 10);

return 0;
}
<小时/>

编辑:我刚刚看到您要求不能使用函数。您可以使用 Barmar 的建议来测试能否被 1、11、111 等整除。然而,棘手的部分是找到正确的除数。

无论如何,我想在这里指出的一点是,您在这里不需要完整的排序算法。

关于c - 如何查看数组中数字是否具有相同的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53326439/

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