题目内容:
从键盘输入一串字符(假设字符数少于8个),以回车表示输入结束,编程将其中的数字部分转换为整型数并以整型的形式输出。
函数原型为 int Myatoi(char str[]);
其中,形参数组str[]对应用户输入的字符串,函数返回值为转换后的整型数。
解题思路的关键是:1)判断字符串中的字符是否是数字字符;2)如何将数字字符转换为其对应的数字值;3)如何将每一个转换后的数字值加起来形成一个整型数。
程序运行结果示例1:
Input a string:7hg09y↙
709
程序运行结果示例2:
Input a string:9w2k7m0↙
9270
程序运行结果示例3:
Input a string:happy↙
0
输入提示信息:"Input a string:"
输入格式: "%7s"
输出格式:"%d\n"
注意:为避免出现格式错误,请直接拷贝粘贴上面给出的输入、输出提示信息和格式控制字符串!
时间限制:500ms内存限制:32000kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int Myatoi(char str[]);
int main()
{
char a[7]; //错误写法: int a;
printf("Input a string:");
scanf("%7s", a); //错误写法 :--> scanf(%7s,a);
printf("%d\n",Myatoi(a));
return 0;
}
int Myatoi(char str[])
{
int i,j;
for(i=0,j=0;str[i]!='\0';i++) //错误写法 --> for (;i!=0; i++)
{
if (str[i]>=48 && str[i]<=57)
{
str[j] = str[i];
j++;
}
}
str[j]='\0'; //注意这一行
return atoi(str); // 错误写法 --> return str[j];
}
该程序设计题要求从用户输入的字符串中提取数字部分,并转换为整型数输出。关键点包括识别数字字符、转换数字值和累加。示例运行展示了不同输入字符串的转换结果。
4236

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



