2014-11-24 3 views
0

У меня есть несколько проблем с этим кодом. Я включил ошибки в конце кода.Ошибки при компиляции кода C

#include <stdio.h> 

int main() 

{ 
void addition(double number1, double number2); /* create the functions */ 
void subtraction(double number1, double number2); 
void division(double number1, double number2); 
void multiplication(double number1, double number2); 
int inputfunc=1; 
double inputnum1=0; 
double inputnum2=0; 
int number1; 
int number2; 
int answer; 

while (inputfunc >= 1 && inputfunc <= 4) /* If function to be performed are those below then continue performing loop */ 

{ 
printf("Press 1 to add two numbers.\n"); 
printf("Press 2 to subtract two numbers.\n"); 
printf("Press 3 to multiply two numbers.\n"); 
printf("Press 4 to divide two numbers.\n"); 
printf("Press 5 to exit.\n"); 
printf("Enter your choice\n"); 
scanf_s("%d", &inputfunc); 

if(inputfunc == 5) /* Exit program if requested via 5 function */ 
return(0); 

printf("Enter both numbers with a space in between."); 
scanf_s("%lf %lf", &inputnum1, &inputnum2); 

void(*func[4])(double, double)={&addition, &subtraction, &division, &multiplication}; 
    (*func[inputfunc-1])(inputnum1, inputnum2); 
    return(0); 
    } 

} 

void addition(double number1, double number2) 
{ 
    double answer; 
    answer=number1+number2; 
    printf("Addition of the two numbers = %lf + %lf = %lf\n", number1, number2, answer); 
    return; 
} 

void subtraction(double number1, double number2) 
{ 
    double answer; 
    answer=number1-number2; 
    printf("By subtracting the two numbers results are %lf - %lf = %lf\n", number1, 
    number2, answer); 
    return; 
} 

void multiplication(double number1, double number2) 
{ 
    double answer; 
    answer=number1*number2; 
    printf("By multiplying the two numbers results are %lf * %lf = %lf\n", number1, 
     number2, answer); 
    return; 
} 

void division(double number1, double number2) 
{ 
    double answer; 
    answer=number1/number2; 
    printf("By dividing the two numbers results are %lf/%lf = %lf\n", number1, 
     number2, answer); 
    return ; 
} 

ошибка C2143: синтаксическая ошибка: отсутствует ';' перед «типа» ошибка C2065: «Func»: необъявленный идентификатор ошибка C2109: индекс требует массив или указатель типа

+2

Пожалуйста, открепите свой код, потому что такие ошибки случаются, если вы пишете код своими ногами. – bitcell

+1

Веселый :-) Btw, @DonCarter, не могли бы вы поддержать тех, кто вам помог? Это стандартная практика, а не только вознаграждение, но и указание другим тем же проблемам, что и на самом деле решало это. Вы можете повышать, а также принимать один ответ, – Mawg

+0

В отличие от некоторых UniCell, я не родился с возможностью писать код. Код, который я написал, был копией и вставкой из Word, которая не всегда транспонируется, поскольку она написана. У вас должно быть больше терпения с новичками. Я занимаюсь этим только три недели! –

ответ

0

Над линией я разместил ниже из вашего кода, вы заканчиваете основной метод со вторым распорка. Это не очень хорошая идея, так как у вас есть код ниже этой скобки.

void(*func[4])(double, double)={&addition, &subtraction, &division, &multiplication}; 
(*func[inputfunc-1])(inputnum1, inputnum2); 
return(0); 
} //end while 

} //end main method 
0

Код компилируется и работает - см it in action here

Некоторые моменты:

  • Это код C, а не C#
  • return(0); помещается внутри цикла while - это предотвратит он запрашивает у пользователя более одного прогона. Переместите это ниже конца цикла while.
  • Объявление массива, содержащий различные функциональные указатели на арифметические операторы не должен быть расположен в пределах цикла в то время - он не меняется между каждой итерацией - т.е. двигаться void(*func[4])(double, double) = { &addition, &subtraction, &division, &multiplication }; к выше while
  • Лучше отступ сделает код более читаемый
  • Самые верхние объявления int number1; int number2; int answer; являются избыточными и должны быть удалены (особенно, поскольку они используются в качестве локальных имен переменных с различными типами в 4 арифметических функциях).

Я сделал вышеуказанные изменения в сниппета (scanf_s был заменен простым scanf в IdeOne не использует MS Compiler).

-1
// the scanf_s function is the secure function for string input, using scanf 

// this version compiles without any warnings, etc under linux gcc 

// this version checks for input errors 
// (except the actual value of the variable inputFunc) 
// I think the use of a switch() statement would be much more robust 
// rather than the use of the function ptr table, although not quite as flexable 

// Notice the function prototypes are outside of any function 
// so the compiler will create the proper code 

#include <stdio.h> 
#include <stdlib.h> // contains exit() and EXIT_FAILURE 

// function prototypes 
void addition(double number1, double number2); 
void subtraction(double number1, double number2); 
void division(double number1, double number2); 
void multiplication(double number1, double number2); 


void(*func[4])(double, double)={&addition, &subtraction, &division, &multiplication}; 

int main() 
{ 

    int inputFunc=1; 
    double inputnum1=0; 
    double inputnum2=0; 

    /* If function to be performed are those 
     below then continue performing loop */ 

    // note: 
    // if the inputFunc is (for instance) 6 then this while loop is exited 
    // however, there was no return statement 
    // for that execution path 

    while (inputFunc >= 1 && inputFunc <= 4) 
    { 
     printf("Press 1 to add two numbers.\n"); 
     printf("Press 2 to subtract two numbers.\n"); 
     printf("Press 3 to multiply two numbers.\n"); 
     printf("Press 4 to divide two numbers.\n"); 
     printf("Press 5 to exit.\n"); 
     printf("Enter your choice\n"); 

     if(1 != scanf(" %d", &inputFunc)) 
     { 
      perror("scanf_s"); 
      exit(EXIT_FAILURE) ; 
     } 

     // implied else, scanf for which command was successful 

     // note: there should be some checking here 
     //  to assure that the input was in the valid range '1...5' 

     if(inputFunc == 5) 
     { /* then, Exit while loop if requested via 5 function */ 
      // note: good program practice is to put the return 
      //  at the bottom of the function 
      break; 
     } 

     printf("Enter both numbers with a space in between."); 
     if(2 != scanf(" %lf %lf", &inputnum1, &inputnum2)) 
     { 
      perror("scanf for 2 input numbers"); 
      exit(EXIT_FAILURE); 
     } 

     // implied else, scanf for two input numbers successful 

     // exec the desired function 
     (*func[inputFunc-1])(inputnum1, inputnum2); 
    } 
    return(0); // to avoid compiler warning 
} 

void addition(double number1, double number2) 
{ 
    double answer; 
    answer=number1+number2; 
    printf("Addition of the two numbers = %lf + %lf = %lf\n", number1, number2, answer); 
    return; 
} 

void subtraction(double number1, double number2) 
{ 
    double answer; 
    answer=number1-number2; 
    printf("By subtracting the two numbers results are %lf - %lf = %lf\n", 
     number1, 
     number2, 
     answer); 
} 

void multiplication(double number1, double number2) 
{ 
    double answer; 
    answer=number1*number2; 
    printf("By multiplying the two numbers results are %lf * %lf = %lf\n", 
     number1, 
     number2, 
     answer); 
} 

void division(double number1, double number2) 
{ 
    // note: this should check that number2 is NOT 0, to avoid divide by zero error 
    double answer; 
    answer=number1/number2; 
    printf("By dividing the two numbers results are %lf/%lf = %lf\n", 
     number1, 
     number2, 
     answer); 
} 
+0

Это прекрасно работало, благодаря вам и всем остальным для ввода. У меня есть и буду продолжать читать ваши ответы, чтобы я мог избежать будущих ошибок такого рода. Еще раз спасибо! –

Смежные вопросы