繁体   English   中英

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

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

我是 C 的新手,正在为这段代码苦苦挣扎。 我需要使用结构从用户输入中获取两名运动员的英尺和英寸,然后计算每位运动员的英寸总和以确定获胜者。 我遇到的问题是返回的值没有任何意义。 我的猜测是它与获取值的地址而不是实际值有关,但是在更改了一些东西之后我只是以错误或程序崩溃告终。 任何帮助表示赞赏。

#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;
}

您的代码几乎没有问题:

  • 每当您使用 float 时要使用的格式说明符是%f而不是您使用%d

  • 尝试向前声明您的calculateInches()方法。 将其写在main()方法之上或尝试使用 function 原型。 看看这个链接

  • 提及 arguments 到 function float calculateInches(float feet, int inches)的正确类型。 相关问题

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

暂无
暂无

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

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