2012-09-09 90 views
0

所以我想寫一個函數,接收一個浮點值,返回一個浮點值,並顯示在主要與printf。我不斷收到同樣的錯誤: markup2.c:58:錯誤:衝突的類型「用getPrice」 markup2.c:46:錯誤:「用getPrice」以前的隱式聲明在這裏我正在學習C,不知道爲什麼這是給我一個錯誤

我在哪裏做的錯誤?我嘗試過對所有接觸GetPrice的類型進行類型轉換,但仍然沒有運氣。有人能解釋我做錯了什麼嗎?

#include<stdio.h> 

// define the constant MARKUP as float value 0.1 
#define MARKUP 0.1 

int main() 
{ 
    // declare variables 
    char proceed; 
    float value; 
    float markupValue; 

    // display welcome message to user and inform them of markup rate 
    printf("\nThank you for using Chad Hammond's markup calculator.\n"); 
    printf("The current markup rate is %.1f%c.\n",MARKUP*100,'%'); 

    // ask user if they want to perform a markup 
    printf("Would you like to markup an item? y/n:\n"); 
    scanf("%c", &proceed); 

    // if yes, proceed to next step 
    if(proceed == 'y') 
    { 
     // prompt user for the price of item to be marked up 
     printf("Please enter a wholesale value to markup: "); 
     scanf("%f", &value); 

     // display input back to user 
     printf("The wholesale value you entered was: %c%.2f\n",'$', value); 
     markupValue = (value*MARKUP); 

     // display amount of increase 
     printf("The dollar amount of this increase will be: %c%.2f\n",'$', markupValue); 

     // display total price after increse 
     printf("The price for this item after markup is: %c%.2f\n",'$', (float)GetPrice(value)); 
    }else 
     // if user did not want to markup an item, belittle them with sarcasm 
     printf("Well, if you didn't want to markup an item you should have just used a Ti-83 and left me alone!\n\n"); 
    // display exit message 
    printf("Thank you for using HammondInstruments Markup Calculator, goodbye.\n"); 

    // return that program has completed 
    return 0; 
} 

float GetPrice(float value) 
{ 
    float output; 
    value += value*MARKUP; 
    output = value; 
    return (float)output; 
} 
+2

用'gcc -Wall -Wextra -o標記markup.c'進行編譯,你將看到錯誤:) – polslinux

回答

3

您需要在main之前聲明或定義GetPrice

+0

謝謝你,工作。我習慣於Java,你可以在main之前或之後有一個方法,它運行良好。很高興這是一個簡單的錯誤,我一直在摸索我的頭幾個小時,試圖看看我的功能邏輯是不正確的!謝謝你們! – cHam

+0

是的,這個對於C來說是非常具體的。既然你提到過Java,我也會指出,與Java不同的是,在你的函數的開始部分聲明所有的變量被認爲是一個很好的習慣)。另外,你能否「接受」我的回答? –

+1

@DeepanjanMazumdar,不僅僅是良好的做法。它曾經是必需的。 – chris

1

您不應該首先聲明GetPrice嗎?然後main

1

您的主要問題是,由於您沒有在main之前聲明一個,所以編譯器會給您一個GetPrice的默認聲明,它與您的不匹配,因此存在衝突。你應該main前加一個原型,或有移動整個功能:

float GetPrice(float); 
//main 
float GetPrice(float value){...} 

float GetPrice(float value){...} 
//main 
3

C期望的,看看它的功能,然後才能使用它們(向前聲明)。在聲明它之前,您已在main中使用GetPrice(函數定義在main之後)。

當你的編譯器看到使用GetPrice,它假定這是它目前還沒有看到一個功能,併產生隱含聲明,它看起來像int GetPrice()。稍後,當它看到函數聲明時,它會看到實函數簽名不同於隱式聲明,並引發錯誤。

的溶液,因此,是main之前要麼限定GetPrice,或main之前使用形式float GetPrice(float);向前聲明。前向聲明(就像你在#include的各種頭文件中實際發現的那樣)告訴編譯器該函數存在,但是將它的定義留給後面的(甚至是另一個文件)。

+0

非常感謝您的詳細解釋,現在它非常有意義! – cHam

相關問題