By Jalan
题干
数字合法性判断,请注意,.1和1.都是合法的
PS:这种地方我总觉得要么测试用例里体现出来,要么题干中得说一下,但是都没有.
例子
例1
输入
7
5 -3.2 aaa 9999 2.3.4 7.123 2.35
输出
ERROR: aaa is not a legal number
ERROR: 9999 is not a legal number
ERROR: 2.3.4 is not a legal number
ERROR: 7.123 is not a legal number
The average of 3 numbers is 1.38
题解
第一次
思路
判断数字的合法性,-应该出现在最前面,小数点前只能有数字和负号,小数点后有且只能有数字,并且不能超过2个.
编写用时
25分钟
代码
CPP
#include <bits/stdc++.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
bool isLegal(string &temp)
{
int size = temp.length();
int negativeIndex = -1;
int negativeCounter = 0;
int dotIndex = -1;
int behindDotCount = 0;
int frontDotCount = 0;
int i = 0;
bool haveDot = false;
for (; i < size; i++)
{
if (temp[i] == '-')
{
if (frontDotCount != 0) //-只能出现在最前面
{
return false;
}
negativeIndex = i;
++negativeCounter;
if (negativeCounter >= 2)
{
return false;
}
continue;
}
if (temp[i] >= '0' && temp[i] <= '9')
{
if (i < negativeIndex)
{
return false;
}
++frontDotCount;
continue;
}
if (temp[i] == '.')
{
dotIndex = i;
haveDot = true;
break;
}
return false; //都不是则不合法
}
++i;
if (haveDot)
{
for (; i < size; i++) //点后只允许出现数字且不能超过2
{
if (temp[i] >= '0' && temp[i] <= '9')
{
++behindDotCount;
if (behindDotCount > 2)
{
return false;
}
continue;
}
return false;
}
}
double t = stof(temp);
if (t < -1000 || t > 1000)
{
return false;
}
else
{
return true;
}
}
int main(int argc, char const *argv[])
{
int n;
cin >> n;
double total = 0.0;
int legalCounter = 0;
for (int i = 0; i < n; i++)
{
char temp[40];
scanf("%s", temp);
string temp2(temp);
if (isLegal(temp2))
{
total += stof(temp2);
legalCounter++;
}
else
{
printf("ERROR: %s is not a legal number\n", temp);
}
}
if ((double)legalCounter == 0)
{
printf("The average of %d numbers is Undefined", legalCounter);
}
else if (legalCounter == 1)
{
printf("The average of 1 number is %.2lf", total);
}
else
{
printf("The average of %d numbers is %.2lf", legalCounter, total / (double)legalCounter);
}
return 0;
}
运行用时
编译器请用clang++.
结尾
看在我写了这么多注释的份上可以给我点个赞嘛,求求惹=]砰砰砰,给我加点写下去的油呀
@.@
也欢迎关注我的CSDN账号呀=]
**开心code每一天**