变量未初始化?

时间:2016-04-10 18:58:45

标签: c++

对于作业问题,我必须定义一个可以在程序中用来表示分数的结构,以及一个可用于设置分数值的set函数,以及一个打印的打印函数很好的分数。我们给出了主要功能,并根据问题输出

(2/3)(1/5)(3/5)

这是我写的:

#include "library.h"
struct fraction
{
    int numerator;
    int denominator;
};

void set (fraction st, int n, int d)
{
    if (d>0)
    {
        n = st.numerator;
        d = st.denominator;
    }
}

void print(fraction st)
{
    int x = st.numerator;
    int y = st.denominator;
    print("(x/y)");
    print(" ");
}

void main()
{
    fraction a, b, c;
    set(a, 2, 3);
    set(b, 1, 5);
    set(c, 3, 5);
    print(a);
    print(b);
    print(c);
}

如果您想知道“library.h”是我的大学用作大多数标准包含的快捷方式。

我一直收到错误,即在没有初始化的情况下使用变量'a'。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

按值将a,b,c传递给set()。当然,它们在main()(和print())中未初始化。试试这个:

void set (fraction &st, int n, int d)
{
    if (d>0)
    {
        //n = st.numerator;
        //d = st.denominator;
        // I suppose this part should be:
        st.numerator = n;
        st.denominator = d;
    }

    /* Edit, thanks to @Tyler S comments:
       Not sure what author needs, but something like this
       should be here to really avoid uninitialized values. 

       Other options:
       Use unsigned int if you use only positive integers ( d>0 ).
       Use exceptions to handle negative inputs, zero denominator..
    */
    else
    {
        st.numerator = 1;
        st.denominator = 1;
    }
 }

在main()中:

set(a, 2, 3);
set(b, 1, 5);
set(c, 3, 5);

我还将print(..)更改为void print(const fraction &st)。没有必要通过价值。想象一下更大的数据结构 - 复制只是为了打印它是浪费时间。

我建议您查看pass by value/referenceconst correctness

答案 1 :(得分:1)

如果set函数需要定义fraction,那么您应该为st.numeratorst.denominator成员变量分配值nd喜欢这样:

void set (fraction st, int n, int d)
{
    if (d>0)
    {
        st.numerator = n;
        st.denominator = d;
    }
}

您还应该通过引用将fraction变量传递到set函数,例如:void set(fraction& st, ...)或指针void set(fraction* st, ...),以便获得任何结果。

相关问题