【问题标题】:Check if input is a string in C# after converting it to a double [duplicate]在将输入转换为双精度后检查输入是否是 C# 中的字符串 [重复]
【发布时间】:2017-04-01 18:45:25
【问题描述】:

我正在开发一个控制台应用程序,它是 C# 中的一个简单计算器,我想检查用户是否输入了字符串而不是数字/小数。相反,我得到了一个破坏程序的 System.Format 异常。我不确定如何告诉程序在看到字符串字符时不要中断。我使用 do while 循环作为在用户输入负数或任何其他无效值时重新提示用户的一种方式。

这是我的代码:

using System;


namespace Calc
{
    public class Calc
    {
        public static void Main()
        {

        ///Declare variables
        double p,r,y;
        string input1, input2, input3;



        ///Prompt user to reenter value if the input is illegal
        do
        {
            ///Prompt the user for the principal
            Console.Write("Enter the principal: ");
            input1 = Console.ReadLine();
            p = double.Parse(input1);
        } while(p < 0 ); 


        ///Prompt the user for the rate
        Console.Write("Enter the rate: ");
        input2 = Console.ReadLine();
        r = double.Parse(input2);

        ///Prompt user to reenter value if the input is illegal
        do 
        {
            ///Prompt the user for the rate
            Console.Write("Enter the rate: ");
            input2 = Console.ReadLine();
            r = double.Parse(input2);

        } while(r < 0);



        ///Prompt user to reenter value if the input is illegal
        do 
        {
            ///Prompt the user for the number of years
            Console.Write("Enter the number of years: ");
            input3 = Console.ReadLine();
            y = double.Parse(input3);
        } while (y < 0);

        ///Calculate the user input using the mortgage rate formula
        double p1 = (r / 1200.0);
        double m = y * 12;
        double nm = 0 - m;
        double month = p * p1 / (1 - System.Math.Pow((1 + p1), nm));



        //Output the result of the monthly payment
        Console.WriteLine(String.Format("The amount of the monthly payment is: {0}{1:0.00}", "$", month));
        Console.WriteLine();
        Console.WriteLine("Press Enter to end the calculator program. . .");
        Console.Read();
    }
}
}

【问题讨论】:

标签: c# asp.net string double decimal


【解决方案1】:

您可以使用返回boolTryParse 来判断转换是否成功:

bool IsValid = double.TryParse(input2,out r);

现在您可以检查IsValid是否返回true是否是一个有效值,否则您可以提示用户重新输入:

    bool IsValid = false;
    ///Prompt user to reenter value if the input is illegal
    do 
    {
        ///Prompt the user for the rate
        Console.Write("Enter the rate: ");
        input2 = Console.ReadLine();
        IsValid = double.TryParse(input2, out r);

    } while(!IsValid && r < 0);

【讨论】:

  • 这个解释对我来说最有意义
【解决方案2】:

使用Double.TryParse

将数字的字符串表示形式转换为其双精度 浮点数等效。返回值指示是否 转换成功或失败。

这样,你可以在使用它之前获取数字是否可以转换......

【讨论】:

    猜你喜欢
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多