2015-02-21 2 views
1

Я не могу заставить свой код работать должным образом. Вот оно:Невозможно передать информацию между функцией и основным

#include <stdio.h> 

void intro_msg(); 
float compass_value(); 
float direction(); 

int main (void) 
{ 

    float compass; 

    intro_msg() ; 

    compass_value(compass); 

    direction(compass); 

    return (0) ; 

} 

void intro_msg(void) 
{ 
    printf("Welcome to the Compass Program \n \n"); 
} 

float compass_value(compass) 
{ 
    printf("Please enter a value for the compass direction. (0 - 360 degress) : "); 
    scanf("%f", &compass); 
    printf("You entered %f degrees \n" , compass); 
    return(compass); 
} 


float direction(compass) 
{ 
    if (compass >= 354.38 && compass <= 360.00){ 
     printf("You are heading North \n"); 
    } 
    else if (compass >= 0.0 && compass <= 39.37){ 
     printf("You are heading North \n"); 
    } 
    else if (compass >= 39.38 && compass <= 84.37){ 
     printf("You are heading Northeast \n"); 
    } 
    else if (compass >= 84.38 && compass <= 129.37){ 
     printf("You are heading East \n"); 
    } 
    else if (compass >= 129.38 && compass <= 174.37){ 
     printf("You are heading Southeast \n"); 
    } 
    else if (compass >= 174.38 && compass <= 219.37){ 
     printf("You are heading South \n"); 
    } 
    else if (compass >= 219.38 && compass <= 264.37){ 
     printf("You are heading Southwest \n"); 
    } 
    else if (compass >= 264.38 && compass <= 309.37){ 
     printf("You are heading West \n"); 
    } 
    else if (compass >= 309.38 && compass <= 354.37){ 
     printf("You are heading Northwest \n"); 
    } 
    else 
    { 
     printf("You did not enter a value between 0 - 360 degrees"); 
    } 
} 

Я пытаюсь получить степень между 0 - 360 от пользователя, записать его, а затем определить направление они сталкиваются (север, юг, северо-восток и т.д.), но мое значение для компаса никогда не записывается.

Сразу после запроса пользователю значение, я иду распечатать значение, и я получаю 0.0, а не то, что пользователь вводил. Что я здесь делаю неправильно?

+0

У меня есть «{» место под моим int main (void) в моем фактическом коде, я по ошибке удалил его перед тем, как поставить этот вопрос. Так что это не проблема. –

+3

Если вы внесли ошибку в код, который вы опубликовали, это не проблема, отредактируйте свой вопрос и исправьте его, а не произнесите это в комментариях. Информация тега (например, язык, который вы используете) относится к тегам, а не к названию. –

+0

Хорошо, спасибо за эту информацию. –

ответ

0

В декларации

float direction(compass) 

какой тип вы думаете compass это? (Подсказка: это не float или double.)


Вот как я хотел бы написать эту программу (проверено):

#include <stdio.h> 

#define ARRAY_SIZE(A) (sizeof A/sizeof A[0]) 
void intro_msg (void) 
{ 
    printf ("Welcome to the Compass Program\n\n"); 
} 

float compass_value (void) 
{ 
    double direction; 
    int bad = 1; 
    do { 
     printf ("Please enter a value for the compass direction (0 to 360 degrees): "); 
     fflush (stdout); 
     if (1 == scanf ("%lf", &direction)) 
      bad = 0; 
    } while (bad); 
    printf ("You entered %f degrees\n", direction); 
    return direction; 
} 

static const struct { 
    float lo, hi; 
    const char *name; 
} dirs [] = { 
    {354.38, 360.0, "North"}, 
    { 0.0, 39.37, "North"}, 
    { 39.37, 84.37, "Northeast"}, 
    { 84.37, 129.37, "East"}, 
    {129.37, 174.37, "Southeast"}, 
    {174.37, 219.37, "South"}, 
    {219.37, 264.37, "Southwest"}, 
    {264.37, 309.37, "West"}, 
    {309.37, 354.37, "Northwest"}, 
}; 

void direction (double compass) 
{ 
    int j; 
    for (j = 0; j < ARRAY_SIZE (dirs); ++j) 
     if (compass >= dirs [j] .lo && compass <= dirs [j] .hi) 
     { 
      printf ("Direction is %s\n", dirs [j] .name); 
      return; 
     } 
    printf ("Direction is not between 0 and 360 degrees.\n"); 
} 

int main (void) 
{ 
    double compass; 

    intro_msg(); 
    compass = compass_value(); 
    direction (compass); 
    return 0; 
} 
+0

Это тип по умолчанию? Должно ли это поплавок (поплавок компаса) –

+0

@JesseT: Действительно. Каков тип по умолчанию? – wallyk

+0

Тип по умолчанию: int –

0

Это должно исправить ваши проблемы

#include <stdio.h> 

void intro_msg(); 
float compass_value(float);  // You had not specified Argument type 
float direction(float);   // You had not specified Argument type 

int main (void) 
{ 

    float compass; 

    intro_msg() ; 

    compass_value(compass); 

    direction(compass); 

    return (0) ; 

} 

void intro_msg(void) 
{ 
    printf("Welcome to the Compass Program \n \n"); 
} 

float compass_value(float compass) // You did not specify type 
{ 
    printf("Please enter a value for the compass direction. (0 - 360 degress) : "); 
    scanf("%f", &compass); 
    printf("You entered %f degrees \n" , compass); 
    return(compass); 
} 


float direction(float &compass)   // You did not specify type, also made it a reference 
{ 
    if (compass >= 354.38 && compass <= 360.00){ 
     printf("You are heading North \n"); 
    } 
    else if (compass >= 0.0 && compass <= 39.37){ 
     printf("You are heading North \n"); 
    } 
    else if (compass >= 39.38 && compass <= 84.37){ 
     printf("You are heading Northeast \n"); 
    } 
    else if (compass >= 84.38 && compass <= 129.37){ 
     printf("You are heading East \n"); 
    } 
    else if (compass >= 129.38 && compass <= 174.37){ 
     printf("You are heading Southeast \n"); 
    } 
    else if (compass >= 174.38 && compass <= 219.37){ 
     printf("You are heading South \n"); 
    } 
    else if (compass >= 219.38 && compass <= 264.37){ 
     printf("You are heading Southwest \n"); 
    } 
    else if (compass >= 264.38 && compass <= 309.37){ 
     printf("You are heading West \n"); 
    } 
    else if (compass >= 309.38 && compass <= 354.37){ 
     printf("You are heading Northwest \n"); 
    } 
    else 
    { 
     printf("You did not enter a value between 0 - 360 degrees"); 
    } 
} 

Теперь проблемы с вашим кодом заключались в том, что вы не указали тип аргумента в объявлении функции и определениях. Вы также передавали компас по значению, из-за которого значение, которое вы принимали от пользователя в compass_value, не было помещено в ваш compass в основном. Итак, он всегда показывал север. Чтобы исправить это, пройдите compass по ссылке, как указано.

Если вы не хотите, чтобы пройти по ссылке, этот код поможет вам

#include <stdio.h> 

void intro_msg(); 
float compass_value(float);   // You had not specified Argument type 
float direction(float );    // You had not specified Argument type 

int main (void) 
{ 

    float compass; 

    intro_msg() ; 

    compass=compass_value(compass); // Since the function was returning a compass, assign that value to the compass in main() 

    direction(compass); 

    return (0) ; 

} 

void intro_msg(void) 
{ 
    printf("Welcome to the Compass Program \n \n"); 
} 

float compass_value(float compass)  // You did not specify type 
{ 
    printf("Please enter a value for the compass direction. (0 - 360 degress) : "); 
    scanf("%f", &compass); 
    printf("You entered %f degrees \n" , compass); 
    return(compass); 
} 


float direction(float compass)    // You did not specify type 
{ 
    if (compass >= 354.38 && compass <= 360.00){ 
     printf("You are heading North \n"); 
    } 
    else if (compass >= 0.0 && compass <= 39.37){ 
     printf("You are heading North \n"); 
    } 
    else if (compass >= 39.38 && compass <= 84.37){ 
     printf("You are heading Northeast \n"); 
    } 
    else if (compass >= 84.38 && compass <= 129.37){ 
     printf("You are heading East \n"); 
    } 
    else if (compass >= 129.38 && compass <= 174.37){ 
     printf("You are heading Southeast \n"); 
    } 
    else if (compass >= 174.38 && compass <= 219.37){ 
     printf("You are heading South \n"); 
    } 
    else if (compass >= 219.38 && compass <= 264.37){ 
     printf("You are heading Southwest \n"); 
    } 
    else if (compass >= 264.38 && compass <= 309.37){ 
     printf("You are heading West \n"); 
    } 
    else if (compass >= 309.38 && compass <= 354.37){ 
     printf("You are heading Northwest \n"); 
    } 
    else 
    { 
     printf("You did not enter a value between 0 - 360 degrees"); 
    } 
} 
0

Я думаю, вы знаете, что вы на самом деле проходите переменную компасу в compass_value() по значению. Означает, что изменение не будет отражено в переменной компаса главной функции.

Я вижу, что вы возвращаете значение чтения, но вы не получаете его во что-либо при вызове compass_value() в своей основной функции. Попытайтесь получить его:

compass = compass_value(compass); 
Смежные вопросы