【发布时间】: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();
}
}
}
【问题讨论】:
-
查看标记的重复项。无论您是在处理
int、double、DateTime还是任何其他可解析的类型,完全相同的建议都适用。另请参阅stackoverflow.com/questions/531397/… 上的讨论
标签: c# asp.net string double decimal