将结构数据传递给变量 C++?

Passing a struct data to a variable C++?

首先,我想为我糟糕的英语道歉,并提前感谢您的阅读和帮助。

基本上我有两个包含 3 个整数的结构: 数字 分数答案

然后我有一个名为 addSubFractions 的 class,它将两个 numbers 结构类型作为参数和 return s 是 fractionAnswers 结构类型。我的目标是将 addSubFractions class 中的 return 分配给名为 numbers 类型结构变量]答案

我是 C++ 的新手,我认为我能够从逻辑上做到这一点,我尽可能多地搜索,但没有任何有用的信息。

这里有一部分代码对我不起作用:

int main() {
numbers first, second, answer ;

cout << "Enter fraction" ;
cin >> first.wholeNumber ;
cin >> first.numerator   ;
cin >> first.denominator ;
cout << "Enter second fraction" ;
cin >> second.wholeNumber ;
cin >> second.numerator ;
cin >> second.denominator ;


answer = addSubFractions(first, second) ;

cout << "Your answer is:" <<  answer.numerator << "/" << answer.denominator ;

return 0 ;}

这是另一个class我说的

    fractionAnswers addSubFractions(numbers firstFraction, numbers secondFraction) {
    numbers answerFraction, holdFraction1, holdFraction2      ;
    fractionAnswers someAnswers               ;

    //Multiply to get same denominator
    holdFraction1.denominator   =   firstFraction.denominator   *   secondFraction.denominator ;
    holdFraction2.denominator   =   firstFraction.denominator   *   secondFraction.denominator ;

    //Numerator multiplication to match new denominator
    holdFraction1.numerator     =   firstFraction.numerator     *   secondFraction.denominator ;
    holdFraction2.numerator     =   secondFraction.numerator    *   firstFraction.denominator  ;


    //Reduce fractions first
    while (true) {
        if(!reduceFractions(holdFraction1))
            break;
    }

    //Reduce fractions second
        while (true) {
            if(!reduceFractions(holdFraction2))
                break;
        }

        someAnswers.numeratorAns     =   holdFraction1.numerator + holdFraction2.numerator ;
        someAnswers.denominatorAns   =   holdFraction2.denominator                  ;
return someAnswers ;
}

这是reduceFractions

bool reduceFractions(numbers Fractions) {
    bool answer ;

    for (int i = Fractions.numerator ; i >= 2 ; i--) {       //This will keep running until i = the GFC for both numerator & denominator
        if ((((Fractions.numerator % i) == 0) && (Fractions.denominator % i) == 0)) {

            Fractions.numerator     /=   i ;
            Fractions.denominator   /=   i ;
            answer                   =   true ;
        }
    }

    answer   =   false ;
    return answer ;

}

这些是结构

struct numbers {
    int numerator   ;
    int denominator ;
    int wholeNumber ;
};

struct fractionAnswers {
    int numeratorAns   ;
    int denominatorAns ;
    int wholeNumberAns ;
};

这段代码不应该编译,对吗?您不能将 fractionAnswers 类型的值分配给 numbers 类型的变量,即使它们具有相同的成员布局。一些选项是:

  • addSubFractions的return类型改为numbers

  • answer = addSubFractions(first, second) ;改为fractionAnswers temp = addSubFractions(first, second); answer.numerator = temp.numeratorAns; answer.denominator = temp.denominatorAns; answer.wholeNumber = temp.wholeNumberAns;