c - 我不希望它返回的类型的函数返回值

标签 c

对于学校的一道题,我需要将一个 ASCII 字符串转换为一个十进制值。我编写了一个函数来执行此操作并将返回类型指定为 unsigned short,如下面的代码所示。

#include <stdio.h>
unsigned short str_2_dec(char* input_string, int numel);
int main()
{
  short input;
  char input_string[6]= "65535";

  input = str_2_dec(input_string, 5);

  printf("Final Value: %d", input);
  return 0;
}
unsigned short str_2_dec(char* input_string, int numel)
{
  int factor = 1;
  unsigned short value = 0;
  int index;

  for(index=0; index <(numel-1); index++)
  {
    factor *= 10;
  }

  for(index = numel; index > 0; index--)
  {
    printf("Digit: %d; Factor: %d; ", *(input_string+(numel-index))-48, factor);
    value += factor * ((*(input_string+(numel - index))-48));

    printf("value: %d\n\n", value);

    factor /= 10;
  }
  return value;
}

运行此代码时,程序打印 -1 作为最终值而不是 65535。它似乎无论如何都在显示相应的有符号值。看起来很简单,但我找不到答案。将不胜感激。

最佳答案

str_2_dec() 的返回类型是 unsigned short 但您将值存储在(有符号的)short 变量中。您应该将您的变量声明为适当的类型,否则您将遇到您所观察到的问题。

在这种情况下,您将 "65535" 转换为 unsigned short,其位模式为 FFFFHex。该位模式被重新解释为(带符号的)short,即十进制值 -1

你应该把你的 main() 改成这样:

int main()
{
    unsigned short input; /* to match the type the function is returning */
    char input_string[6]= "65535";

    input = str_2_dec(input_string, 5);

    printf("Final Value: %hf", input);
    return 0;
}

关于c - 我不希望它返回的类型的函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7495056/

相关文章:

c - 使用 "*"符号获取字符作为密码并与您的密码匹配

c++ - 整数可以类型转换为指向整数的指针吗?

c - 使用命名管道在两个进程之间发送字符串

c++ - Codeblocks 16.01 中警告被视为错误

在 C 中复制一个 int8_t 数组

c - Sublime Text 2 编译错误(我认为)

c - 我找不到为什么我的程序总是说太低

c - select() 和 C 上带有动态缓冲区的非阻塞 recv

c - 运行一个简单的 libpcap 示例时出错

c - Fopen 返回 null 除非在那里进行探索?