需要编写一个函数,将字符串转换为双精度而不调用任何内置实用程序,例如, , , ,atof()
或Double.parseDouble()
任何Double.valueOf()
类似[NSString doubleValue]
方法。[NSScanner scanDouble]
std::stringstream
问问题
327 次
2 回答
3
const char *s = "-123.456";
int sign = 1;
int hasdp = 0;
int dplaces = 0;
float f = 0.0;
while(*s) {
switch (*s) {
case '-': sign = -1; break;
case '.': hasdp = 1; break;
default:
f *= 10;
f += *s - '0';
break;
}
s++;
if (hasdp) dplaces++;
}
f *= sign;
int i;
for (i = 1; i < dplaces; i++) f /= 10;
// we need to start from 1 in order to get
// the correct result, this is a property
// of this algorithm
现在f
将包含解析值,前提是其格式正确(可选 - 前缀、可选小数点后跟 1 个或多个小数位。
于 2012-09-04T09:59:23.913 回答
2
尝试以下操作:
- (void)myMethod:(NSString *)numberString{
int i = 0;
float number = 0.0;
while ([numberString length] > i) {
NSString *myChar = [numberString substringWithRange:NSMakeRange(i, 1)];
NSLog(@"%@", [numberString substringWithRange:NSMakeRange(i, 1)]);
i++;
if ([myChar isEqualToString:@"1"]){
number = number * 10 + 1;
} else if ([myChar isEqualToString:@"2"]){
number = number * 10 + 2;
} else if ([myChar isEqualToString:@"3"]){
number = number * 10 + 3;
} else if ([myChar isEqualToString:@"4"]){
number = number * 10 + 4;
} else if ([myChar isEqualToString:@"5"]){
number = number * 10 + 5;
} else if ([myChar isEqualToString:@"6"]){
number = number * 10 + 6;
} else if ([myChar isEqualToString:@"7"]){
number = number * 10 + 7;
} else if ([myChar isEqualToString:@"8"]){
number = number * 10 + 8;
} else if ([myChar isEqualToString:@"9"]){
number = number * 10 + 9;
} else if ([myChar isEqualToString:@"0"]){
number = number * 10 + 0;
}
}
}
于 2012-09-04T09:54:38.250 回答