简体   繁体   English

结果在字符串到整数之间的转换期间减1(并且只有特定的字符串长度值)

[英]Result Decremented by 1 during a conversion between string to integer (and only with specific values of string length)

I'm writing a program in C that converts a string of n characters into an integer only if this string's first character is the minus symbol. 我正在用C语言编写一个程序,只有当这个字符串的第一个字符是减号时才会将n个字符的字符串转换为整数。 The program is the following: 该计划如下:

#include <string.h>
#include <stdio.h>
#include <math.h>

int StringToInt(char *string){
    int i=0;
    int integer=0;
    int length = strlen(string);
    if (string[0]=='-'){
        for (i=1; i<length; i++){
        integer += (string[i]-48)*pow(10, (length-1-i));
        }return (integer*(-1));
    }else{
        return 0;
    }
}

My program works fine when I call the function above with a string with an odd value of string length, while otherwise it returns the right value but decremented by one. 当我使用字符串长度为奇数值的字符串调用上面的函数时,我的程序工作正常,否则返回正确的值但递减1。 Now I'll make it clearer with an example: suppose I create a string called "Number" and I assign to this the number "-234". 现在我将通过一个例子更清楚:假设我创建了一个名为“Number”的字符串,并为此分配了数字“-234”。 If we put this string in the function above, the string's length will be calculated as 4. The function in this case won't return -234, but -233. 如果我们将此字符串放在上面的函数中,则字符串的长度将计算为4.在这种情况下,函数不会返回-234,而是返回-233。 If, instead of -234, I had assigned to the string a number like "-1456", the function would have returned the correct number. 如果,而不是-234,我已经为字符串分配了一个类似“-1456”的数字,该函数将返回正确的数字。

I'm pretty sure it's just rounding errors. 我很确定这只是错误的四舍五入。 When you cast 0.999999 as an int you get 0. Thus, any floating point error that results in a number like 2047.999999 will be interpreted as 2047 instead of the more accurate 2048, which will look like it's decremented by 1. 当您将0.999999转换为int时,您得到0.因此,任何导致数字如2047.999999的浮点错误都将被解释为2047而不是更准确的2048,这看起来会减少1。

As John Bollinger suggested in a comment, just add each character to 10 times the current value: 正如John Bollinger在评论中建议的那样,只需将每个字符添加到当前值的10倍:

#include <string.h>
#include <stdio.h>

int string_to_int(char *string) {
  int i=0;
  int integer=0;
  int length = strlen(string);
  if (string[0] == '-') {
    for (i=1; i<length; i++) {
      integer = 10 * integer + string[i]-'0';
    }

    return -integer;
  } else {
    return 0;
  }
}

int main(int argc, char **argv) {
  if (argc < 2)
    return 1;

  printf("Result: %d\n", string_to_int(argv[1]));
  return 0;
}

I prefer to say '0' rather than 48 since it clarifies your intent (converting a character to the digit it represents). 我更喜欢说'0'而不是48,因为它澄清了你的意图(将一个字符转换为它所代表的数字)。

I suggest the next code, it's based in the recommendations made in comments: 我建议下一个代码,它基于评论中提出的建议:

#include <string.h>
#include <stdio.h>


int StringToInt(const char* string){
    int lenght = strlen(string);
    if (lenght && string[0] == '-'){
        int integer = 0;
        for (int i = 1; i < lenght; ++i) {
            // Check if it is not a character valid.
            if (string[i] < '0' || string[i] > '9') {
                // Returns the integer processed so far.
                return -integer;
            }
            integer = 10 * integer + string[i] - '0'; // Like John Bollinger suggests
        }
        return -integer;
    } else {
        return 0;
    }
}


int main(int argc, char **argv) {
    fprintf(stderr, "%d\n", StringToInt(""));
    fprintf(stderr, "%d\n", StringToInt("-123"));
    fprintf(stderr, "%d\n", StringToInt("-1736734"));
    fprintf(stderr, "%d\n", StringToInt("-1999"));
    fprintf(stderr, "%d\n", StringToInt("-123"));
    fprintf(stderr, "%d\n", StringToInt("-234"));
    fprintf(stderr, "%d\n", StringToInt("-180."));
    fprintf(stderr, "%d\n", StringToInt("-200.99"));
    fprintf(stderr, "%d\n", StringToInt("-aaa"));

    const char* msg = "-301";
    fprintf(stderr, "%d\n", StringToInt(msg));
    return 0;
}

I suggest check if the character is not valid (ie: it is not between '0' and '9'): 我建议检查角色是否无效(即:它不在'0'和'9'之间):

if (string[i] < '0' || string[i] > '9') {
    // Returns the integer processed so far.
    return -integer;
}

Once you find a character not valid, return the integer processed so far. 找到无效字符后,返回到目前为止处理的整数。

Output: 输出:

0
-123
-1736734
-1999
-123
-234
-180
-200
0
-301

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM