以下代码有效,但计算错误。请告诉我应该如何计算它,以便输出与输入相同。请不要更改或添加新代码,除非它只是计算部分。
目前的结果只是例如:
键入一个将转换为double的字符串:12.23
字符串12.23 - >数字0.012
#include <stdio.h>
void main()
{
char input[100];
printf("Type a String which will be converted to a double: ");
scanf("%s", input);
double number = 0.0;
double divider = 1.0;
double sign = 1.0;
enum { Start, End, Error, A, B, C, D } state = Start;
int i = 0;
while (state != End && state != Error)
{
char ch = input[i];
i++;
switch (state)
{
case Start:
if (ch == '+' || ch == '-')
{
state = A;
if (ch == '-')
{
sign = -1.0;
}
}
else if (ch >= '0' && ch <= '9')
{
state = B;
number = number * 10.0 + ch - '0';
}
else
{
state = Error;
}
break;
case A:
if (ch >= '0' && ch <= '9')
{
state = B;
number = number * 10.0 + ch - '0';
}
else
{
state = Error;
}
break;
case B:
if (ch >= '0' && ch <= '9')
{
state = B;
number = number * 10.0 + ch - '0';
}
else if (ch == '.')
{
state = C;
divider = divider * 10.0;
}
else if (ch == '\0')
{
state = End;
}
else
{
state = Error;
}
break;
case C:
if (ch >= '0' && ch <= '9')
{
state = D;
divider = divider * 10.0;
}
else
{
state = Error;
}
break;
case D:
if (ch >= '0' && ch <= '9')
{
state = D;
divider = divider * 10.0;
}
else if (ch == '\0')
{
state = End;
}
else
{
state = Error;
}
break;
}
}
if (state == End)
{
printf("string %s -> number %g \n", input, sign * number / divider);
}
else
{
printf("Enter a valid number! \n");
}
}
答案 0 :(得分:1)
纠正你奇怪的代码
状态$active_group = 'default';
$active_record = TRUE;
$db['default']['failover'] = array(
array(
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'com',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE
),
array(
'hostname' => 'localhost2',
'username' => 'root',
'password' => '',
'database' => 'ABC',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE
)
);
和C
应为
D
状态case C:
if (ch >= '0' && ch <= '9')
{
state = D;
divider = divider * 10.0;
number = number * 10.0 + ch - '0';
}
else
{
state = Error;
}
break;
case D:
if (ch >= '0' && ch <= '9')
{
state = D;
divider = divider * 10.0;
number = number * 10.0 + ch - '0';
}
else if (ch == '\0')
{
state = End;
}
else
{
state = Error;
}
break;
应该避免增加分隔符:
B