【问题标题】:There is data type error in code where the type is boolean instead of integer代码中存在数据类型错误,其中类型是布尔值而不是整数
【发布时间】:2021-12-12 14:55:00
【问题描述】:

所以我在 C# 中编写了一个简单的代码:-

检查坐标是否在圆内

但是当我编译下面的程序时

public static void Main() 
        {
            int[] centre={0,0};
            int r=5;
            Console.Write("Coordinates: ");
            int pointX=Convert.ToInt16(Console.ReadLine());
            int pointY=Convert.ToInt16(Console.ReadLine());
            bool checkFirst=((pointX - centre[0])^2)+((pointY - centre[1])^2)== r^2;
            string check= checkFirst ? "true" : "false";
            Console.WriteLine(
                "It is {0} that {1},{2} is inside circle {3} of radius {4}.",
                check,pointX,pointY,centre,r);
            
        }

pointX - center 的行上,显示的错误是 减法在 bool 中,我无法平方

如果我去掉中心并写任何整数,答案是正确的。

请帮忙!!!

【问题讨论】:

  • ^ 不是“幂”运算符(不存在),而是按位异或
  • 仅供参考,intInt32,因此正确的解析是 Convert.ToInt32 - 但这不是问题的根源。 Int16 == 短
  • 注意:“centre”的“ToString”是“System.Int32[]”,而不是“(0,0)” - 您需要单独指定值

标签: c# arrays


【解决方案1】:

使用Math.Pow方法计算幂:

static void Main(string[] args)
{
    int[] centre = { 0, 0 };
    int r = 5;
    Console.Write("Coordinates: ");
    int pointX = Convert.ToInt16(Console.ReadLine());
    int pointY = Convert.ToInt16(Console.ReadLine());
    bool checkFirst = Math.Pow(pointX - centre[0], 2) + Math.Pow(pointY - centre[1], 2) <= Math.Pow(r, 2);
    string check = checkFirst ? "true" : "false";
    Console.WriteLine($"It is {check} that {pointX},{pointY} is inside circle {centre} of radius {r}.");
}

【讨论】:

  • 呃。 Math.Pow(pointX - centre[0])*(pointX - centre[0]) 贵很多。
  • @Enigmativity 但是可读性更强:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
  • 2015-04-22
  • 2011-12-18
  • 1970-01-01
  • 2019-02-04
  • 2016-04-08
相关资源
最近更新 更多