Given an integer
n
, write a C program to count the number of digits that are in the same position after forming an integerm
with the digits inn
but in ascending order of digits. For example, if the value ofn
is 351462987 then value ofm
will be 123456789 and digits 4 and 8 will be in the same position.
这是我的代码:
#include<stdio.h>
void bubble(int a[],int length)
{
for (int i=0;i<length;i++)
{
for (int j=0;j<length;j++)
{
if (a[j]>a[j+1])
{
int t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
}
int check(int a[],int b[],int length)
{
int count=0;
for (int i=0;i<length;i++)
{
if (a[i]==b[i])
{
count=i;
break;
}
}
return count;
}
int length(int n)
{
int l;
while (n!=0)
{
n=n/10;
l++;
}
return l;
}
void main()
{
int n,arrn[100],temp[100];
scanf("%d",&n);
int l=length(n);
for (int i=0;i<l;i++)
{
arrn[l-i-1]=n%10;
temp[l-i-1]=arrn[l-i-1];
n=n/10;
}
bubble(temp,l);
int c=check(arrn,temp,l);
printf("%d",c);
}
我能够编译代码,但是当我执行它时,需要很长时间才能显示段错误。
最佳答案
简单回答,使用调试器。
您的代码存在一些问题:
在
length
函数,l
未初始化,因此可以具有任意初始值。就您而言,您可能希望从 0 开始。int l = 0;
您的
check
函数可能无法执行您想要的操作。如所写count
不是计数,而是数字匹配位置的索引。因为有一个break
语句 block 中,循环将在第一个匹配项后退出,因此返回值将是第一个匹配项的位置,如果没有找到匹配项,则返回值为 0。- 您的
bubble
当i
时,函数会超出一项等于length - 1
当您访问项目a[j + 1]
时在超出范围的内循环中。在这种情况下,从 1 而不是从 0 开始并比较索引i - 1
处的项目会更简单。索引为i
的项目.
一些额外的说明:
建议在运算符周围以及分隔多个声明的逗号后添加空格,以提高可读性。以下是一些可读性更高的行示例。
int n, arrn[100], temp[100]; int count = 0; for (int i = 0; i < length; i++)… if (a[i] == b[i])… arrn[l - i - 1] =n % 10; temp[l - i - 1] = arrn[l - i - 1]; int check(int a[], int b[], int length)
您应该编写一个函数并确保其正常工作,而不是一次编写多个函数。顺便说一句,将数字拆分为数字的循环也可以是一个函数。
- 尝试使用较小数字(例如 12 或 21)的函数
- 为变量使用更好的名称。
arrn
和temp
不是很清楚。original
和sorted
可能会更好。
关于c - 冒泡排序需要很长时间然后出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54042793/