分别对字符串(112和12)按编码和数字进行比较。
在sort()函数中,参数要求为:传递字符串数组、数组大小和字符串比较的函数指针。
最后一个要求字符串比较的函数指针是怎么写的呢?麻烦顺着我的思路写一下,还需要定义什么函数吗,帮我补齐一下,谢谢
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int compare_by_ascii(const chars1,const chars2);
int compare_by_digits(const chars1,const chars2);
void main()
{
char*strs[2]={"112","12"};
sort(strs,2,compare_by_ascii);
sort(strs,2,compare_by_digits);
}
sort(const char*strs[],int n,这里应该怎么写? )
{
int i,j;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if
int compare_by_ascii(const chars1,const chars2)
{
return strcmp(s1,s2);
}
int compare_by_digits(const chars1,const chars2)
{
int v1=atoi(s1);
int v2=atoi(s2);
if(s1>s2)
{
return 1;
}
else if(v1==v2)
{
return 0;
}
else
return -1;
}
你题目的解答代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int compare_by_ascii(const char *s1,const char *s2);
int compare_by_digits(const char *s1, const char *s2);
void sort(char *strs[], int n, int (*fp)(const char *s1, const char *s2))
{
int i, j;
char *t;
for (i = 0; i < n-1; i++)
{
for (j = i + 1; j < n; j++)
{
if(fp(strs[i], strs[j])>0)
{
t = strs[i];
strs[i] = strs[j];
strs[j] = t;
}
}
}
}
int compare_by_digits(const char *s1, const char *s2)
{
int v1 = atoi(s1);
int v2 = atoi(s2);
if (v1 > v2)
{
return 1;
}
else if (v1 == v2)
{
return 0;
}
else
return -1;
}
int compare_by_ascii(const char *s1, const char *s2)
{
return strcmp(s1,s2);
}
void main()
{
char *strs[4] = {"112", "12", "31", "2"};
sort(strs, 4, compare_by_ascii);
for (int i = 0; i < 4; i++)
{
printf("%s\n", strs[i]);
}
sort(strs, 4, compare_by_digits);
for (int i = 0; i < 4; i++)
{
printf("%s\n", strs[i]);
}
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!