简体   繁体   English

C - 使用结构从用户输入添加距离

[英]C - Adding Distance from User Input using struct

I am very new to C and am struggling with this code.我是 C 的新手,正在为这段代码苦苦挣扎。 I need to get the feet and inches of two athletes from user input using a structure, then total the inches of each athlete to determine the winner.我需要使用结构从用户输入中获取两名运动员的英尺和英寸,然后计算每位运动员的英寸总和以确定获胜者。 The issue I'm having is that the value being returned doesn't make any sense.我遇到的问题是返回的值没有任何意义。 My guess is it has something to do with getting the address of the value instead of the actual value, but after changing some things around I just end up with errors or the program crashing.我的猜测是它与获取值的地址而不是实际值有关,但是在更改了一些东西之后我只是以错误或程序崩溃告终。 Any help is appreciated.任何帮助表示赞赏。

#include <stdio.h>
#include <stdlib.h>

//Distance Structure
struct Distance
{
    int feet;
    float inches;
};

int main() {

    //Initialize athelete structures
    struct Distance athlete1;
    struct Distance athlete2;

    //Get values for athlete 1
    printf("Enter the distance for athlete 1\n");
    printf("Feet: ");
    scanf("%d", &athlete1.feet);
    printf("Inches: ");
    scanf("%d", &athlete1.inches);

    //Get values for athlete 2
    printf("Enter the distance for athlete 2\n");
    printf("Feet: ");
    scanf("%d", &athlete2.feet);
    printf("Inches: ");
    scanf("%d", &athlete2.inches);

    //Convert values to inches
    float total1 = calculateInches(athlete1.feet, athlete1.inches);
    float total2 = calculateInches(athlete2.feet, athlete2.inches);

    //Print distance in inches
    printf("\nAthlete 1 has a distance of %d inches\n", total1);
    printf("Athlete 2 has a distance of %d inches\n\n", total2);

    //Print the winner
    if(total1 > total2){
        printf("Athlete 1 wins!");
    }
    else if(total1 < total2){
        printf("Athlete 2 wins!");
    }
    else{
        printf("Tie!");
    }
    return 0;
}

//Calculate Inches
int calculateInches(feet, inches){
    float total;
    total = (feet*12) + inches;
    return total;
}

There are few issues with your code:您的代码几乎没有问题:

  • The format specifier to be used whenever you are using float is %f instead you are using %d每当您使用 float 时要使用的格式说明符是%f而不是您使用%d

  • Try forward declaring your calculateInches() method.尝试向前声明您的calculateInches()方法。 Write it above the main() method or try using a function prototype.将其写在main()方法之上或尝试使用 function 原型。 have a look at this link看看这个链接

  • Mention the right types for the arguments to the function float calculateInches(float feet, int inches) .提及 arguments 到 function float calculateInches(float feet, int inches)的正确类型。 Related question相关问题

Working example: https://ideone.com/jsMZgv工作示例: https://ideone.com/jsMZgv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM