k的不相关值

时间:2016-10-10 20:13:25

标签: c

程序陷入无限循环。我尝试获取k的值,但它显示为854.似乎我在checktrue()函数中提交了一个错误。试过几个小时。没问题。

#include <stdio.h>
#include <conio.h>
int checktrue(int *p);
int k;
long long int m;
void main()
{
long long int fir=1;
long long int pfir=0,n=0;
long long int sec=2;
long long int sum=fir;
clrscr();
while (n!=5)
{
sum=sum+sec;
pfir=fir;
fir=sec;
sec=sec+pfir;
n=checktrue(&sec);

}
printf("The sum is %llu",sum);
getch();
}
int checktrue(int *p)
{
k=0;
m=*p;
while(m!=0)
{
m=m/10;
k++;
}
return(k);
}

1 个答案:

答案 0 :(得分:1)

您将指针传递给sec,允许函数checktrue()操纵输入。如果你摆脱它我得到输出15

#include <stdio.h>
#include <stdlib.h>

unsigned long long checktrue(unsigned long long p);
int main()
{
  unsigned long long fir = 1, n = 0;
  unsigned long long sec = 2;
  unsigned long long sum = fir;
  while (n != 2) {
    sum = sum + sec;
    fir = sec;
    sec = sec + fir;
    n = checktrue(sec);
  }
  printf("The sum is %llu\n", sum);
  exit(EXIT_SUCCESS);
}

unsigned long long checktrue(unsigned long long p)
{
  unsigned long long k = 0;
  while (p != 0) {
    p /= 10;
    k++;
  }
  printf("Exited Succesfully %llu\n", k);
  return k;
}