如何在C#中读取用户的十进制数?

时间:2017-09-08 13:36:23

标签: c#

所以我已经有3周的新编程了,我正在尝试使用C#创建一个基本的Console计算器。我不知道如何从用户读取小数(例如5.5)。普通的整数(例如5)可以工作。我收到以下异常错误

  

发生了'System.FormatException'类型的未处理异常   mscorlib.dll中

     

其他信息:输入字符串的格式不正确。

这是代码:

Console.WriteLine(
  "Hi there, My name is Mohammed.\n" +
  "Today we are going to be doing several calculations.\n\n" +
  "These would include Addition, Subtraction, Multiplication and Division. ");

Console.WriteLine("To get started, please hit the space key.");
Console.ReadKey();

Console.WriteLine("We will start with a addition. Please enter the first number.");
double num01 = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Now enter the second number");
double num02 = Convert.ToDouble(Console.ReadLine());

double ans01 = (num01 + num02);
Console.WriteLine(num01 + "+" + num02 + " is equals to " + ans01 + 
    "\nGreat, now lets move on to subtraction. Please enter the first number.");

2 个答案:

答案 0 :(得分:5)

我建议方法提取,如下所示:

#import "RNHomeKit.h"
#import <HomeKit/HomeKit.h>
#import <React/RCTLog.h>

@implementation RNHomeKit

@synthesize myHomeManager;

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(createHome) {
  RCTLog(@"FAKELY CREATING HOME");
  self.myHomeManager = [[HMHomeManager alloc] init];
  self.myHomeManager.delegate= self;

  [self.myHomeManager addHomeWithName: @"Matt's Awesome Home" completionHandler:^(HMHome *home, NSError *error) {
    RCTLog(@"REALLYING CREATING HOME");
    if (!error) {
      RCTLog(@"Created Home : %@",home.name);
    } else {
      RCTLog(@"Error: %@", error);
    }
  }];
}

@end

然后我们可以使用例程

using System.Globalization;

...

private static double ReadDouble(string title)
{
    while (true) 
    {
        Console.WriteLine(title);

        string userInput = Console.ReadLine();

        double result;

        // We use CultureInfo.InvariantCulture to ensure that
        // decimal separator is dot (.). i.e. we expect 5.5 input
        if (double.TryParse(userInput, 
                            NumberStyles.Any, 
                            CultureInfo.InvariantCulture, 
                            out result))
        {
            return result;
        }

        Console.WriteLine("Sorry, incorrect format. Enter it again, please.");  
    }
}

答案 1 :(得分:0)

您应该检查计算机上的当前文化。您可以转到Control Panel并点击Region and Language。从那里,点击底部的Additional settings按钮。它应该带你到Customize Format页面如下

Customize Format Page

此页面告诉您如何在控制台上输入十进制数字。以上步骤适用于Win 7机器。然后,您可以尝试以下C#代码来验证Visual Studio上即时窗口的工作情况

double.Parse("5.5");
double.Parse("5,5");

正确的格式不会在即时窗口(或临时代码)中抛出异常

此外,可以使用以下代码

通过C#提取相同的Decimal symbol
System.Globalization.CultureInfo.CurrentCulture.NumberFormat.PercentDecimalSeparator