2015-07-28 75 views
0

我必须找到一个数字的平方/ 12345/- 完成了。我想使程序有点复杂,我有这样的:C#找到一个数字的平方

using System; 

class Program 
{ 
    static void Main() 
    { 
     Console.WriteLine("The square of the number 12345 is"); 
     Console.WriteLine(Math.Sqrt(12345)); 
     Console.WriteLine("Enter a number to calculate the square:"); 
     int numVal = int.Parse(Console.ReadLine()); 
     Console.WriteLine("The square of your number is" + " " + Math.Sqrt(numVal)); 
     Console.WriteLine("Do you wish to enter another number? Yes/No"); 
     string input = Console.ReadLine(); 
      if (input == "Yes") 
      { 
       Console.WriteLine("Enter a number to calculate the square:"); 
       int newNum = int.Parse(Console.ReadLine()); 
       Console.WriteLine("The square of your number is" + " " + Math.Sqrt(newNum)); 
      } 
      else 
      { 
       Console.WriteLine("Have a nice day!"); 
      } 

    } 
} 

现在有这样的问题:程序询问时,如果我想进入另一个号码,答案应该是用大写字母/是的,没有/。即使我以小写字母输入answear,是否有办法使其工作?/是,否/?

+2

你想的方形或平方根? [Math.Sqrt](https://msdn.microsoft.com/en-us/library/system.math.sqrt(v = vs.110).aspx) –

+0

尝试使用'IndexOf'方法中的'OrdinalIgnoreCase',而不是比较'=='运算符。 –

+0

尝试 input.toLowerCase == “是” http://stackoverflow.com/questions/6371150/comparing-two-strings-ignoring-case-in-c-sharp – Blinky

回答

2

根据您的输入,下面行将反应。

if(string.Equals(input, "Yes", StringComparison.CurrentCultureIgnoreCase)) 
{ 
    // Your stuffs 
} 

if(string.Equals(input, "Yes", StringComparison.OrdinalIgnoreCase)) 
{ 
    // Your stuffs 
} 

注: OrdinalIgnoreCase字符代码进行比较没有文化方面。这对于精确比较是很好的,例如登录名,但不适用于排序具有不寻常字符(如é或ö)的字符串。这也比较快,因为在比较之前没有额外的规则可供使用。

欲了解更多信息:Go Herehere

+0

我不会建议Ordinal(如果英文字符串是硬编码,并且始终是CurrentCulture,如果它可能是本地化的,那么最好不变),但不要怀疑**这是唯一正确的答案**。 –

1

你可以试试:

... 
string input = Console.ReadLine(); 
      if (input.ToUpper() == "YES") 
      { 
       ... 
+0

谢谢!它工作得很好,我学到了一些新东西。我总是寻找最快和最简单的方法来使我的程序工作。 :) –

+0

我会记住这一点,非常感谢你,阿德里亚诺! –

+0

@NitinSawant,抱歉,我无法真正理解你的评论。 ..我的回答很直接,并直接回答Q. – apomene

-2
string.Equals(input, "Yes", StringComparison.OrdinalIgnoreCase) 
+0

使用序数比较(而不是CurrentCulture或InvariantCulture,取决于上下文)会消除String.Equals()的一半好处,并且它不会比天真的ToUpper()好。 –

相关问题