题目
请编写程序,主函数中输入一行字符串,内有数字字符和非数字字符,调用函数求该字符串中数字字串最大的数字,并在主函数中显示最大的数字,限定该字符串中数字字串最多不超过10个。
实现代码
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define N 100
int findmax(char* s, float* pmax);//定义的功能函数,传地址对其max修改
void main(void)
{
char array[N];//输入的字符串
char temp[N];//中转字串
int i;
float max = 0;
puts("please input a string");
gets_s(array);
if (findmax(array, &max) == 0)//空串
printf("no number in the string\n");
else
printf("maximum number is %g", max);
}
int findmax(char* s, float* pmax)
{
int findflag = 0,flag=0,no=0,tempcnt=0;//flag用于判断现在读到的数字的位置
char* p,temp[10];//p指针访问数组,temp存储字串
for (p = s;*p != '\0';p++)
{
if (*p >= '0' && *p <= '9' || *p == '.')
{
flag = 1;
temp[tempcnt++] = *p;//将字符存储
}
else if (flag == 1)
{
flag = 0;
findflag = 1;
temp[tempcnt] = '\0';//数字字串结束后补‘\0’
tempcnt = 0;
number++;//数字字串个数
if (number == 1)
{
*pmax = atof(temp);//atof函数可以直接将字符串转换为浮点数
}
else
{
if (atof(temp) > *pmax)
{
*pmax = atof(temp);//设标签排序法
}
}
}
}
if (flag == 1)//如果最后一个还是数字的处理
{
temp[tempcnt] = '\0';
number++;
if (number == 1)
*pmax = atof(temp);
else
{
if (atof(temp) > *pmax)
*pmax = atof(temp);
}
}
return findflag;
}
本文介绍如何使用C语言编写程序,从输入的包含数字和非数字字符的字符串中找出最长的数字子串,并在主函数中显示这个最大数字。程序限定字符串中的数字子串不超过10个。
3362

被折叠的 条评论
为什么被折叠?



