无法在C中获得特定序列但能够在Python

时间:2015-08-02 07:37:15

标签: python c while-loop stdio

我正在尝试使用C语言启动并运行一个非常简单和基本的逻辑。下面的代码在python上正确,但我无法使用C获得相同的结果。

//Python Code
a = 2
while True:
    a=a*2
    print(a)

使用上面的Python代码,我能够生成特定的序列,但是使用以下C代码,我无法生成相同的结果。

//C Code
#include <stdio.h>
int main(){
long int a = 2;
while (1){
    a=a*2;
    printf(a);
}
return 0;
}

我无限地获得0。为什么我无法在C中获得序列。

编辑:我在Arduino上使用稍加修改的代码运行此程序,因此我无法使用printf。

4 个答案:

答案 0 :(得分:0)

C中的

printf 与Python中的print相同。 This是一个描述如何使用printf的页面。基本上,您提供了一个格式字符串,描述了打印参数的位置,内容和方式,然后是要打印的可变数量的参数。您想使用printf("%ld\n", a);

答案 1 :(得分:0)

    #include <stdio.h>
int main()
{
  int count, n, t1=0, t2=1, display=0;
  printf("Enter number of terms: "); /** Series for how many terms **/
  scanf("%d",&n);
  printf("Fibonacci Series: %d+%d+", t1, t2); 
  count=2;
  while (count<n)  
  {
      display=t1+t2;
      t1=t2;
      t2=display;
      ++count;
      printf("%d+",display);
  }
  return 0;
}

答案 2 :(得分:0)

您要打印的序列不是斐波那契序列。它是比率为2的几何序列。请参阅维基百科:FormatterFibonacci numbers

假设你真的想要序列2,4,8 ....,

printf的用法不同。使用

printf("%ld", a);

C也不会处理超过2 ^ 32的整数。使用long,它可以处理最多2 ^ 64,但无论哪种情况你都会得到溢出,即。生成63个数字后,这些数字最终会超出范围。 Python内置了Big Integers,C没有。

答案 3 :(得分:0)

好吧,也许你正在使用Arduino上的其他print()错误..在Arduino标签上发布此内容并查看。