【问题标题】:C# Use of Unassigned Variable in a math expressionC# 在数学表达式中使用未赋值变量
【发布时间】:2013-10-09 01:37:15
【问题描述】:

我的任务是制作一个可以接受披萨订单的程序。我给了用户两个单选按钮来选择大小(大号 6 美元,超大号 12 美元)和四个单选按钮来选择浇头的数量(1、2、3、4)。我想出了一个计算含税成本的方程式(C=1.13(0.75(x-1)+1)+S,x 是浇头,S 是尺寸)。

我的问题是,一旦我尝试对方程式进行编码,它就会说在倒数第二行中使用未分配变量 numbToppings 和 size 存在错误。

关于为什么会发生这种情况以及如何解决它的任何想法。

        const double taxes = 1.13;
        const double toppings = 0.75;
        double size;
        double numToppings;
        double costInitial;
        double costTotal;

        if (radLarge.Checked == true)
        {
            size = 6;
        }

        else if (radXLarge.Checked == true)
        {
            size = 12;
        }

        if (rad1.Checked == true)
        {
            numToppings = 1;
        }

        else if (rad2.Checked == true)
        {
            numToppings = 2;
        }

        else if (rad3.Checked == true) 
        {
            numToppings = 3;
        }

        else if (rad4.Checked == true) 
        {
            numToppings = 4;
        }

        costInitial = ((toppings * numToppings - 1) + 1) + size;
        costTotal = taxes * costInitial; 

【问题讨论】:

    标签: c# variables compiler-errors radio-button


    【解决方案1】:

    这样做很简单

    double numToppings = 0;
    

    将其设置为零。

    原因:您正在对 numToppings 进行一些计算,而编译器不够智能,无法确定您已经处理了所有可能的条件,并且无论如何都会初始化 numToppings

    更多信息请阅读Strange behaviour of switch case with boolean value

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 2020-02-25
      • 2010-11-16
      • 2017-04-07
      • 2014-12-30
      • 2021-06-18
      • 1970-01-01
      相关资源
      最近更新 更多