简体   繁体   English

结构的新手,为什么我的程序没有运行?

[英]New to structs, how come my program is not running?

The program asks the user for a numerator and denominator in the enter function, then it needs to simplify and then display it. 该程序在输入功能中要求用户提供分子和分母,然后需要进行简化然后显示。 I tried running it and my program broke. 我尝试运行它,但程序中断了。

Any tips on how to do this? 有关如何执行此操作的任何提示?

I am still trying to learn how to do structures. 我仍在尝试学习如何做结构。

    #define _CRT_SECURE_NO_WARNINGS
    #include <stdio.h>

    struct Fraction
    {
        int numerator;
        int denominator;
    };

    void enter(struct Fraction *choice)
    {
        printf("Numerator: \n");
        scanf("%d", choice->numerator);

        printf("Denominator: \n");
        scanf("%d", choice->denominator);
    }

    void simplify(struct Fraction *reduce)
    {
        reduce->numerator = reduce->numerator / reduce->numerator;
        reduce->denominator = reduce->denominator / reduce->denominator;
    }

    void display(const struct Fraction *show)
    {
        printf("%d / %d", show->numerator, show->denominator);
    }

    int main(void)
    {
        struct Fraction f;

        printf("Fraction Simplifier\n");
        printf("===================\n");

        enter(&f);
        simplify(&f);
        display(&f);
    }

Problem 1 问题1

The lines 线

    scanf("%d", choice->numerator);
    scanf("%d", choice->denominator);

need to be: 需要:

    scanf("%d", &choice->numerator);
    scanf("%d", &choice->denominator);
    //         ^^ Missing

Problem 2 问题2

The following lines: 以下几行:

    reduce->numerator = reduce->numerator / reduce->numerator;
    reduce->denominator = reduce->denominator / reduce->denominator;

are equivalent to: 等效于:

    reduce->numerator = 1.0;
    reduce->denominator = 1.0;

You need code to compute the GCD of the numerator and denominator and then use: 您需要代码来计算分子和分母的GCD,然后使用:

    double gcd = get_gcd(reduce->numerator, reduce->denominator);
    reduce->numerator = reduce->numerator/gcd;
    reduce->denominator = reduce->denominator/gcd;

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

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