Конфликтующие типы и предыдущее объявление x было здесь ... что? - PullRequest
8 голосов
/ 02 апреля 2011

Я учил себя C несколько месяцев, когда у меня есть время, и я столкнулся с проблемой, я не уверен, как ее исправить.

В частности, когда я пытаюсь скомпилировать это с помощью gcc, Я получаю:

geometry.c:8: error: conflicting types for ‘trapezoid’
geometry.c:7: note: previous declaration of ‘trapezoid’ was here
geometry.c:48: error: conflicting types for ‘trapezoid’
geometry.c:7: note: previous declaration of ‘trapezoid’ was here
geometry.c:119: error: conflicting types for ‘trapezoid_area’
geometry.c:59: note: previous implicit declaration of ‘trapezoid_area’ was here
geometry.c: In function ‘cone_volume’:
geometry.c:128: error: called object ‘3.14100000000000001421085471520200371742248535156e+0’ is not a function
geometry.c: In function ‘cylinder_volume’:
geometry.c:136: error: called object ‘3.14100000000000001421085471520200371742248535156e+0’ is not a function

Теперь, я думаю, что мне может понадобиться настроить функции, но, опять же, я не уверен.

Похоже, что он хочет прочитать PI, который я определил как 3.141, как функцию.Есть ли способ, которым я могу избежать использования магического числа 3.141 (хотя оно намного меньше магического числа, чем другие)?

//Geometric formulae
#include <stdio.h>
#include <math.h>

#define PI 3.141

float trapezoid(float b1, float b2, float h);
int trapezoid();
float sphere_volume(float r);
int sphere();
float cone_volume(float r, float h);
int cone();
float pyramid_volume(float b, float h);
int pyramid();
float cylinder_volume(float r, float h);
int cylinder();

int main(void) {
        char selection = 0;

        while(selection != 'q') {
                printf("\t--Geometric Formulas--\n");
                printf("\tSelection an option from the menu: ");
                scanf("%c", & selection);
                switch(selection) {
                        case 1: //Trapezoid area
                                printf("%d", trapezoid());
                                break;
                        case 2: //Sphere volume
                                printf("%d", sphere());
                                break;
                        case 3: //Cone volume
                                printf("%d", cone());
                                break;
                        case 4: //Pyramid volume
                                printf("%d", pyramid());
                                break;
                        case 5: //Cylinder volume
                                printf("%d", cylinder());
                                break;
                        default:
                                break;
                }
        }
}
//      --Shape Menus--
//Trapezoid
int trapezoid() {
        float h = 0, b1 = 0, b2 = 0;
        float traparea;

        printf("\tTrapezoid base 1: ");
        scanf("%3f", &b1);
        printf("\tTrapezoid base 2: ");
        scanf("%3f", &b2);
        printf("\tTrapezoid height: ");
        scanf("%3f", &b2);

        traparea = trapezoid_area(b1, b2, h);

        printf("\tTrapezoid Area: %3f\n", traparea); }

//Sphere
int sphere() {
        float r = 0;
        float spherevol;

        printf("\tSphere radius: ");
        scanf("%f", &r);

        spherevol = sphere_volume(r);

        printf("\tSphere volume: %3f\n", spherevol); }

//Cone
int cone() {
        float r = 0, h = 0;
        float conevol;

        printf("\tCone radius: ");
        scanf("%f", &r);
        printf("\tCone height: ");
        scanf("%f", &h);

        conevol = cone_volume(r, h);

        printf("\tCone volume: %3f\n", conevol); }

//Pyramid
int pyramid() {
        float b = 0, h = 0;
        float pyramidvol;

        printf("\tPyramid base: ");
        scanf("%f", &b);
        printf("\tPyramid height: ");
        scanf("%f", &h);

        pyramidvol = pyramid_volume(b, h);

        printf("\tPyramid volume: %3f\n", pyramidvol); }

//Cylinder
int cylinder() {
        float r = 0, h = 0;
        float cylindervol;

        printf("\tCylinder radius: ");
        scanf("%f", &r);
        printf("\tCylinder height: ");
        scanf("%f", &h);

        cylindervol = cylinder_volume(r, h);

        printf("Cylinder volume: %3f", cylindervol); }

//      --Geometric Formulas--
//Trapezoid Area Computation
float trapezoid_area(float b1, float b2, float h) {
        return ((b1 + b2) * h) / 2; }

//Sphere Volume Computation
float sphere_volume(float r) {
        return ((pow(r,3)) * (4 * PI)) / 3; }

//Cone Volume Computatioin
float cone_volume(float r, float h) {
        return ((PI(pow(r,2)) * h)) / 3; }

//Pyramid Volume Computation
float pyramid_volume(float b, float h) {
        return (b * h) / 3; }

//Cylinder Volume Computation
float cylinder_volume(float r, float h) {
        return (PI(pow(r,2))) * h; }

Ответы [ 6 ]

7 голосов
/ 02 апреля 2011

Любой из них, кто говорит, что было «неявное» определение: это можно решить, предварительно объявив его.Например, вы предварительно объявили float trapezoid и int trapezoid , но не объявили заранее trapezoid_area Как отмечали другие, вы также не можете перегружать в C, как вы можете в C ++.

В некоторых областях вы пытаетесь неявно умножить - например, PI (pow (r,2)) должно быть PI * (pow (r, 2)) .

4 голосов
/ 02 апреля 2011

Ошибки, которые вы видите, связаны с тем, что вы дважды определяете одну и ту же функцию с разными сигнатурами

float trapezoid(float b1, float b2, float h);
int trapezoid();

На основании ваших других определений похоже, что первые trapezoid функции должны называться trapezoid_volume

float trapezoid_volume(float b1, float b2, float h);
int trapezoid();
3 голосов
/ 02 апреля 2011

C не поддерживает перегрузку функций. C ++ делает.

И так как вы случайно объявили trapezoid_volume как trapezoid, вы получите ошибку компилятора.

1 голос
/ 02 апреля 2011
#define PI 3.141

float trapezoid(float b1, float b2, float h);
int trapezoid();

Я думаю, что вы хотите

float trapezoid_volume(...);
/*             ^^^^^^^                 */
1 голос
/ 02 апреля 2011

Вы дважды определили функцию трапеции. С не С ++. Вы не можете определить одну и ту же функцию с разными сигнатурами, как в C ++, используя функции перегрузки.

0 голосов
/ 02 апреля 2011

Чтобы ответить на ваш вопрос об определении PI - число pi обычно определяется в math.h (как M_PI), но, поскольку оно не является частью реального стандарта, вам может потребоваться выполнить некоторую настройку для его получения.

Например, при использовании MSVC вам нужно определить _USE_MATH_DEFINES, чтобы получить его.Информацию библиотеки GNU C см.

...