【问题标题】:Math.Round - Does not round answerMath.Round - 不四舍五入答案
【发布时间】:2015-07-15 21:57:38
【问题描述】:

我想做一个计算周长的程序。虽然,宁愿有一个四舍五入的答案(两位小数)作为七位小数的姿势。但是当我使用Math.Round 方法时,它似乎不圆。我究竟做错了什么?

Console.Write("Circumference Calculator! Enter the radius of the circle: ");
int inputRadius = Convert.ToInt32(Console.ReadLine());
double ans = Math.Sqrt(inputRadius) * Math.PI;
Math.Round(ans, 2);
Console.WriteLine("Your answer is: " + ans + " squared.");

【问题讨论】:

  • 通过分配舍入结果,您实际上是在计算舍入并将结果扔掉而不使用它。作为一般规则,变量只有在你给它们赋值时才会改变(使用=),但传递它们会使它们保持不变。
  • 请不要在“感谢信”中花费一半的帖子,并尽量提供尽可能少的样本...我试图删除一些与您的问题不严格相关的代码 - 随意滚动如果您认为我删除了重要细节,请返回...
  • 请注意,您可能尝试实现的是Formatting a float to 2 decimal places,这通常通过使用适当的字符串格式来完成。

标签: c# math methods


【解决方案1】:

Math.Round 不修改提供的参数 - 它返回一个新值。因此,您必须将其分配回一个变量才能使其工作:

ans = Math.Round(ans, 2);

【讨论】:

    【解决方案2】:

    你必须使用Math.Round的返回值,它不会通过引用来获取变量。

    //Greet user & give instructions
    #region
    Console.WriteLine("Circumference Calculator");
    Console.WriteLine("");
    Console.Write("Welcome to the Circumference Calculator! Please enter the radius of the circle: ");
    #endregion
    
    //Get input from user and calculate answer
    #region
    Console.ForegroundColor = oldColour;
    int inputRadius = Convert.ToInt32(Console.ReadLine());
    double ans = Math.Sqrt(inputRadius) * Math.PI;
    Console.ForegroundColor = ConsoleColor.DarkYellow;
    double roundedAnswer = Math.Round(ans, 2);
    Console.WriteLine("Your answer is: " + roundedAnswer + " squared.");
    #endregion
    

    【讨论】:

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