首页 > 解决方案 > 当用户在 C# 中使用点而不是逗号将小数部分输入到双精度变量中时,如何编写错误消息?

问题描述

亲爱的业余和资深开发人员,

我是一个初学者,最近开始更加认真地学习 C#(我已经在高中时开始涉足 C# 世界,但现在,我更加认真地学习它)。我制作了一个简单的命令提示符应用程序,作为我大学高级编程语言课程的作业:

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

namespace HW_002_01
{
class Program
{
    static void Main(string[] args)
    {
        
        Console.Write("Please enter the length of the triangle's a side (cm)! ");
        double a;
        bool a_if = double.TryParse(Console.ReadLine(), out a);
        Console.Write("Please enter the length of the triangle's b side (cm)! ");
        double b;
        bool b_if = double.TryParse(Console.ReadLine(), out b);
        Console.Write("Please enter the length of the triangle's c side (cm)! ");
        double c;
        bool c_if = double.TryParse(Console.ReadLine(), out c);

        if (a_if == true && a > 0 && b > 0 && c > 0)
        {
            double res1 = a + b;
            if (res1 > c)
            {
                Console.WriteLine("Triangle equality is present.");
            }
            else
            {
                Console.WriteLine("Triangle equality is not present.");
            }
        }
        else if (b_if == true && a > 0 && b > 0 && c > 0)
        {
            double res2 = a + b;
            if (res2 > c)
            {
                Console.WriteLine("Triangle equality is present.");
            }
            else
            {
                Console.WriteLine("Triangle equality is not present.");
            }
        }
        else if (c_if == true && a > 0 && b > 0 && c > 0)
        {
            double ossz3 = a + b;
            if (res3 > c)
            {
                Console.WriteLine("Triangle equality is present.");
            }
            else
            {
                Console.WriteLine("Triangle equality is not present.");
            }
        }
        else
        {
            Console.WriteLine("You cannot make a tringle with these numbers.");
        }

        Console.ReadKey();
    }
  }
}

这个小程序使用用户输入的数字检查三角形中的三角形相等性。它运行良好,但我只是不知道如何发出错误消息,说明程序无法用点而不是理解小数一个逗号。这将是对我的程序的一个很好的修饰,以原谅我的初学者级意大利面条代码。

我希望有人尽快回复。

标签: c#consoleconsole-applicationc#-7.3

解决方案


double.TryParse已经使用您的默认文化检查数字格式。因此,如果点在您的文化数字格式中不存在,并且用户输入它而不是逗号,则double.TryParse返回 false。


推荐阅读