程序损坏,不确定为什么变量错误

时间:2015-03-25 23:23:46

标签: c#

我需要有关类赋值的帮助,我首先使用try-catch但现在他希望我尝试在没有try-catch的情况下进行错误检查。我有它工作,然后他还希望我使用一种方法进行两次执行的数学运算,现在已经破坏了我的程序,我不知道为什么。

该程序应该采用两个数字,然后显示总和,商,产品和差异。但据我所知,数学是用随机数来完成的。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TeamStuff
{
    class Program
    {

        static void Main(string[] args)
        {
            double one = 2, two = 1;
            string check = null;

            while (true)
            {
                Console.WriteLine("Enter number 1: ");
                check = Console.ReadLine();

                if (CheckParse(check, one) == true)
                {
                    one = Convert.ToDouble(check);
                    break;
                }

            }

            while (true)
            {
                Console.WriteLine("Enter number 2: ");
                check = Console.ReadLine();

                if (CheckParse(check, two) == true)
                {
                    two = Convert.ToDouble(check);
                    if (two == 0)
                    {
                        Console.WriteLine("You cannot divide by zero, try again.");
                    }
                    else
                    {
                    one = Convert.ToDouble(check);
                        break;
                    }
                }

            }

            Console.WriteLine("Sum=" + (one + two) +
                "\nProduct= " + (one * two) +
                "\nDifference= " + (one-two) +
                "\nQuotient= " + (one/two)
                );

            Console.ReadLine();
        }


        static Boolean CheckParse(string x, double y)
        {
            return double.TryParse(x, out y);
        }

    }
}

1 个答案:

答案 0 :(得分:0)

                two = Convert.ToDouble(check);
                if (two == 0)
                {
                    Console.WriteLine("You cannot divide by zero, try again.");
                }
                else
                {
                one = Convert.ToDouble(check);
                    break;
                }

这应该是

                two = Convert.ToDouble(check);
                if (two == 0)
                {
                    Console.WriteLine("You cannot divide by zero, try again.");
                }
                else
                {
                    break;
                }

另一方面,你不需要转换两次,你可以通过装箱传递一个值。

    // Notice the out keyword ---------\  /
    //                                  \/
    static Boolean CheckParse(string x, out double y)
    {
        // out keyword-----------\  /
        //                        \/
        return double.TryParse(x, out y);
    }

看看: