输入一个字符串(长度小于50),然后过滤掉所有的非数字字符,得到由数字字符组成的字符串,将其转化为double型结果输出(4位小数)。
测试用例:输入 | 测试用例:输出 |
!1 @2 #3 $4 %5 ^6 &7 *8 (9 )0 | 1234567890.0000
|
abcdEFGH | the digital string is empty!
|
987aaa654bbb321ccc | 987654321.0000
|
000aa 11bb | 11.0000
|
代码如下:
#include <stdio.h>
#include <math.h>
int main()
{
char s[51];
gets(s);
int i, j, count = 0;
double n = 0;
for (i = 0; s[i] != '\0'; ++i) {
if (s[i] >='0' && s[i] <= '9') {
++count;
}
else {
for (j = i; s[j] != '\0'; ++j) {
s[j] = s[j+1];
}
--i;
}
}
if (count != 0) {
for (i = 0; i < count; ++i) {
n += (int)(s[i] - 48) * pow(10, count - i - 1);
}
printf("%.4lf\n", n);
}
else {
printf("the digital string is empty!\n");
}
return 0;
}