【问题标题】:Variable not initialized?变量未初始化?
【发布时间】:2016-07-31 18:10:03
【问题描述】:

对于家庭作业问题,我必须定义一个可以在程序中用于表示分数的结构,以及一个可用于设置分数值的 set 函数,以及一个将打印的 print 函数分数很好。我们得到了 main 函数,根据问题输出应该是

(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”在未初始化的情况下被使用的错误。任何帮助将不胜感激。

【问题讨论】:

  • 如果您认为它初始化,请说明在哪里? (提示,编译器的抱怨是正确的,而不仅仅是a)。
  • 编译器没有准确地告诉你问题出在哪一行吗?
  • Fwiw,set() 中的赋值语句似乎落后了。此外,即使这些已修复,您仍然通过 valueabc 传递给 set(),因此无论如何,main() 中的任何内容都不会更改.
  • void main() ?? main 必须在 C++ 中返回 int

标签: c++


【解决方案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, ...),以便返回任何结果。

【讨论】:

    【解决方案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

    【讨论】:

    • 这仍然很危险,因为如果 d set() 后尝试调用 print在接受的范围内,您可能正在处理一些奇怪的值。如果 OP 使用指针,这种做法很可能会导致分段错误。
    • 是的,但我完全不明白这个条件 - 为什么只检查 d - 避免负分母?负分子呢?我刚刚写了问题的解决方案,但感谢您的评论。
    • 如果目标是简单地避免负值,OP 应该使用无符号整数。但是我相信目标是避免DIV/0,因此应该在set() 方法中将异常作为else 条件抛出。 This stack overflow article 涵盖了足够详细的主题。
    • 我同意,但我认为作者在处理函数调用时不知道exceptions。正如作者所写 - 这是家庭作业。
    • 我同意。我只是提供可能对 OP 或此问题的任何其他潜在读者有用的其他信息。
    猜你喜欢
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 2016-02-24
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多