2014-10-10 63 views
-1

這是我用C語言生成Pascal三角形的代碼。生成pascal三角形時出錯

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

void main() 
{ 
    int i, n, c; 
    scanf("%d", &n); 
    for (i = 0; i < n; i++) 
    { 
     for (c = 0; c <= (n - i - 2); c++) 
      printf(" "); 
     for (c = 0; c <= i; c++) 
      printf("%ld", factorial(i)/(factorial(c)*factorial(i - c))); 
     printf("\n"); 
    } 
    getche(); 
} 

long factorial(int n) 
{ 
    int c; 
    long res = 1; 
    for (c = 1; c <= n; c++) 
     res = res*c; 
    return(res); 
} 

在編譯時它顯示錯誤:

  • 衝突的類型 '因子'

  • 以前隱含的聲明 '因子' 在這裏

我在這裏犯了什麼錯誤?

回答

1

衝突的類型「因子」
以前的隱性「因子」的聲明在這裏

這兩個錯誤指的是一兩件事:該功能factorial應宣佈使用前。
只需在main之前移動定義或在main之前爲其寫入聲明。

我不會爲你寫詳細的解釋,因爲已經有一些例如What is the difference between a definition and a declaration?

+0

非常感謝:D對我來說這是一個愚蠢的錯誤! – 2014-10-10 07:24:48

+0

@shri_wahal我很樂意提供幫助。 :) – starrify 2014-10-10 07:28:33

0

在定義它之前,您正在使用factorialmain。這在C中是合法的,但是會讓編譯器猜測你的函數返回一個int。但是,當達到factorial的定義時,編譯器注意到它實際上返回了一個導致錯誤的long

您可以通過兩種方式解決這個問題:

  1. 互換mainfactorial

  2. 的定義中加入long factorial(int n);介紹的main定義之前的factorial預先聲明。