返回long long unsigned int的函数的返回值不正确

时间:2014-02-06 04:25:14

标签: c

当我从main调用函数wordToInt(c)时,返回值与函数内部的函数不同。

main()
{
    long long  unsigned item;
    char c[6] = "ABCDE";
    item = wordToInt(c);
    printf("Main  The item is :%llu\n",item);
}

long long unsigned wordToInt(char *c)
{
    long long unsigned int k,item=0;
    int i,len;
    int j,p=0;
    len = (int) strlen(c);

    for(i = len-1;i>=0;i--)
    {
        if(c[i] == 'c')
            j = 42;
        else if(c[i] == '*')
            j = 99;
        else
            j = (int) c[i];
        j = j%100;
        k = pow(100,p);
        p++;
        item = item + (j*k);
    }

    printf("Function item is :%llu\n",item);
    return item;
}

该计划的输出是:

Function item is :6566676869
Main  The item is :18446744071686293893

有人能告诉我为什么输出不一致吗?

4 个答案:

答案 0 :(得分:6)

首先 - 注意编译器的警告,它们很重要!

答案 - 因为你在使用它之前没有原型wordToInt(),编译器警告你它没有原型并且假设函数返回了一个int(小于long long)。所以你得到一个返回的int值,而不是很长的。函数中打印的值是正确的,因为函数知道正确的类型。

答案 1 :(得分:2)

wordToInt()之前添加main()声明,或在wordToInt()之前添加main()的正文。无论哪种方式,编译器都会知道wordToInt()的原型,只有这样才能传递参数并正确返回返回值。

答案 2 :(得分:0)

char数组在给定字符串时总是会自动在字符串末尾添加NULL字符,因此大小为6

char c[6] = "ABCDE";

当我使用和不使用更改时运行相同的代码时输出是一致的。

对于字母大小6

Function item is :6566676869
Main  The item is :6566676869

对于字母大小5

Function item is :656667686803780408
Main  The item is :656667686803780408

编辑:我在函数调用之前添加了一个原型。

答案 3 :(得分:0)

我复制并运行了你的程序及其工作。我在两个细分中都找到了相同的结果。我不知道为什么你在主要功能中得到错误的答案。无论如何,这就是我如何做到的。

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

long long unsigned wordToInt(char *c)
{

  long long unsigned int k,item=0;
  int i,len;
  int j,p=0;
  len = (int) strlen(c);

  for(i = len-1;i>=0;i--)
  {
          if(c[i] == 'c')
                  j = 42;
          else if(c[i] == '*')
                  j = 99;
          else
                  j = (int) c[i];
          j = j%100;
          k = pow(100,p);
          p++;
          item = item + (j*k);
  }
  printf("Function item is :%llu\n",item);
  return item;
}

int main()
{
    long long unsigned item;
    char c[5] = "ABCDE";
    item = wordToInt(c);
    printf("Main The item is :%llu\n",item);
    getch();
    return 0;
}

然后我用MinGW编译它:gcc -c yourFileName.c 然后是可执行文件:gcc -o可执行文件yourFileName.o

相关问题