假设我有一个3.50(字符串)的输入,如何解析它以便将其存储为3美元和50美分。美元和美分都是整数,并且不允许atoi。
我考虑到这一点,但显然在C语言中不起作用(假设令牌为3.50):
dollars = int(token); /* dollars is 3 */
cents = atoi(token) - dollars; /* atoi is not allowed but I can't think of anything else */
谢谢!
最佳答案
您将需要修改它们以优雅地处理无效输入,但是这些功能将对有效输入起作用:
int get_dollars(char *str)
{
int i = 0;
int accum = 0;
// While the current character is neither the null-terminator nor a '.' character
while(str[i]&&str[i]!='.')
{
// Shift any previously accumulated values up one place-value by multiplying it by 10
accum *= 10;
// Add the numeric value of the character representation of the digit in str[i] to accum
// (('0'-'9')-0x30=integer value 0-9)
accum+=str[i]-0x30;
// Increment the loop counter
i++;
}
// Return the result
return accum;
}
int get_cents(char *str)
{
int i = 0;
int accum = 0;
int start_pos = 0;
// Get the location of the '.' character so we know where the cent portion begins at
while(str[i]&&str[i]!='.') {i++; start_pos++; }
i = start_pos+1;
// Same algorithm as get_dollars, except starting after the '.' rather than before
while(str[i])
{
accum *= 10;
accum += str[i]-0x30;
i++;
}
return accum;
}