1. Enter a string and convert it to an integer. Note: This is not a positive integer, so you need to consider negative numbers. There is no skill, just calculate it. As long as negative numbers are taken into account, the processing skills are also very important. The core code is as follows:
[Cpp]
// Convert a string to an integer
Int StrToInt (char * str)
{
If (! Str)
Return-Inf;
Int nLen = strlen (str );
Int I = 0;
Int ans = 0;
Bool IsNag = false;
If (str [0] = '-')
{
IsNag = true;
I = 1;
}
For (; I <nLen; ++ I)
{
Ans = ans * 10 + str [I]-'0 ';
}
If (IsNag)
Return-ans;
Else
Return ans;
}
// Convert a string to an integer
Int StrToInt (char * str)
{
If (! Str)
Return-Inf;
Int nLen = strlen (str );
Int I = 0;
Int ans = 0;
Bool IsNag = false;
If (str [0] = '-')
{
IsNag = true;
I = 1;
}
For (; I <nLen; ++ I)
{
Ans = ans * 10 + str [I]-'0 ';
}
If (IsNag)
Return-ans;
Else
Return ans;
} 2. If you enter a string and convert it to a number, there may be a decimal point. The decimal point must be considered. In this way, the decimal point is used to divide the string into two parts: the integer part and the decimal part. Calculate them separately. How to write the code in a concise and good-looking manner is a skill problem. Accumulate it slowly! The Code is as follows:
[Cpp]
// Convert a string to a floating point number
Double StrToDouble (char * str)
{
If (! Str)
Return-Inf; // for the double type, this Inf may not be enough.
Int nLen = strlen (str );
Int I = 0;
Double ans = 0.0;
Bool IsNag = false;
If (str [0] = '-')
{
IsNag = true;
I = 1;
}
// Integer part
For (; I <nLen; ++ I)
{
If (str [I] = '.')
Break;
Ans = ans * 10 + str [I]-'0 ';
}
// Decimal part
Double flag = 10.0;
For (I = I + 1; I <nLen; ++ I)
{
Ans + = (str [I]-'0')/flag;
Flags * = 10.0;
}
If (IsNag)
Return-ans;
Else
Return ans;
}
// Convert a string to a floating point number
Double StrToDouble (char * str)
{
If (! Str)
Return-Inf; // for the double type, this Inf may not be enough.
Int nLen = strlen (str );
Int I = 0;
Double ans = 0.0;
Bool IsNag = false;
If (str [0] = '-')
{
IsNag = true;
I = 1;
}
// Integer part
For (; I <nLen; ++ I)
{
If (str [I] = '.')
Break;
Ans = ans * 10 + str [I]-'0 ';
}
// Decimal part
Double flag = 10.0;
For (I = I + 1; I <nLen; ++ I)
{
Ans + = (str [I]-'0')/flag;
Flags * = 10.0;
}
If (IsNag)
Return-ans;
Else
Return ans;
} 3. OK. Finally, the main function is provided.
[Cpp]
# Include <stdio. h>
# Include <string. h>
Const int Inf = 1e9;
Int main ()
{
Const int N = 20;
Char str [N];
While (scanf ("% s", & str )! = EOF)
{
// Printf ("% d \ n", StrToInt (str ));
Printf ("% lf \ n", StrToDouble (str ));
}
Return 0;
}
# Include <stdio. h>
# Include <string. h>
Const int Inf = 1e9;
Int main ()
{
Const int N = 20;
Char str [N];
While (scanf ("% s", & str )! = EOF)
{
// Printf ("% d \ n", StrToInt (str ));
Printf ("% lf \ n", StrToDouble (str ));
}
Return 0;
}