[Homework] C# Basics - Operators and Expressions - Problem{10} - Point Inside a Circle & Outside of a Rectangle
Здравейте,
как сте решили тази задача. При (x*x) + (y*y) <= (1.5*1.5)raduis не проверява вярно тъй като окръжността е изместена {1, 1}
Здравейте,
как сте решили тази задача. При (x*x) + (y*y) <= (1.5*1.5)raduis не проверява вярно тъй като окръжността е изместена {1, 1}
Ето едно решение от мен:
using System;
class Program
{
 static void Main()
 {
 Console.Write("Please put x: ");
 double x = double.Parse(Console.ReadLine());
 Console.Write("Please put y: "); 
 double y = double.Parse(Console.ReadLine());
 double r = 1.5;
 int circle = 0;
 int rectangle = 0;
 if ((((x * x) - (2 * x) + 1) + ((y * y) - (2 * y) + 1)) <= (r * r))
 {
 circle = 1;
 }
 if ((x >= -1 && x <= 5) && (y >= -1 && y <= 1))
 {
 rectangle = 1;
 }
 if (circle == 1 && rectangle == 0)
 {
 Console.WriteLine("yes");
 }
 else
 {
 Console.WriteLine("no");
 }
 } 
}
Ето и моето решение. Направих, някой обобщителни промени в условието, които включват възможността да се задава големина на радиуса на окръжността, както и размерите на правоъгълника. Програмата може да се усъвършенства като се създаде взможността да се задава и център на окръжността, но това предстоя в по нова версия, :-)! Кода може да се изтегли оттук: http://pastebin.com/h38Bxk9s. Ето го и него в неформатиран вид:
using System;
class PointInsideCircleOutsideRectangle
{
 static void Main()
 {
 bool check;
Console.Write("Please, enter a radius: ");
 double R = double.Parse(Console.ReadLine());
Console.WriteLine("\n" + "Please, determine the borders of the rectangle R, as follow:");
Console.Write("\n" + "Left vertical border \"xMin\": ");
 double xMin = double.Parse(Console.ReadLine());
 
 Console.Write("Left vertical border \"xMax\": ");
 double xMax = double.Parse(Console.ReadLine());
double width = xMax - xMin;
Console.Write("\n" + "Lower horizontal border \"yMin\": ");
 double yMin = double.Parse(Console.ReadLine());
Console.Write("Upper horizontal border \"yMax\": ");
 double yMax = double.Parse(Console.ReadLine());
double height = yMax - yMin;
Console.Write("\n" + "Please, enter \"x\" coordinate of a point: ");
 double x = double.Parse(Console.ReadLine());
Console.Write("Please, enter \"y\" coordinate of a point: ");
 double y = double.Parse(Console.ReadLine());
if ( Math.Pow(x-1, 2) + Math.Pow(y-1, 2) <= Math.Pow(R, 2) && ((x >= xMin || x <= xMax) && (y >= yMin || y <= yMax)) )
 {
 check = true;
 Console.WriteLine("\n" + "Is the point with coordinates ({0};{1}) within the circle K((1;1) {2}) and" + "\n"
 + "out of the rectangle R(top={3}, left={4}, width={5}, height={6}): {7}", x, y, R, yMax, xMin, width, height, check);
 }
 else
 {
 check = false;
 Console.WriteLine("\n" + "Is the point with coordinates ({0};{1}) within the circle K((1;1) {2}) and" + "\n"
 + "out of the rectangle R(top={3}, left={4}, width={5}, height={6}): {7}", x, y, R, yMax, xMin, width, height, check);
 }
 Console.WriteLine();
 }
}
Това е моето решение и също така още един вариант как да направим задачата:
//circle parameters:
 double circleOriginX = 1;
 double circleOriginY = 1;
 double circleRadius = 1.5;
//the points I want to assign to my circle
 double myX = 1;
 double myY = 2.5;
//rectangle parameters:
 double rTop = 1;
 double rLeft = -1;
 double rHeight = 2;
 double rWidth = 6;
//makes the calculation work wherever the circle is
 double myNewX = myX - circleOriginX;
 double myNewY = myY - circleOriginY;
// using the Pythagoras theoreme (x*x) + (y*y) = c*c 
 if ((myNewX * myNewX) + (myNewY * myNewY) <= (circleRadius * circleRadius) 
 && !((myX >= rLeft && myX <= rLeft + rWidth) && (myY <= rTop && myY >= rTop + rHeight ))) 
 { 
 Console.WriteLine("Yes");
 }
 else
 {
 Console.WriteLine("No");
 }
 Console.WriteLine();
Супер!
Ето я и подновената прорама, в която може да се задава центъра на окръжността в конзолата: http://pastebin.com/h38Bxk9s
Ето моето решение:
using System;
class PointInsideaCircleOutsideofaRectangle
 {
 static void Main()
 {
 double x = double.Parse(Console.ReadLine());
 double y = double.Parse(Console.ReadLine());
 bool inCircle = ((x-1)*(x-1)) + ((y-1)*(y-1)) <= (1.5 * 1.5) ;
 bool inRectangle = (x <= 5 && x >= -1) && (y >= -1 && y <= 1);
 if (inCircle && !inRectangle)
 {
 Console.WriteLine("Yes");
 }
 else
 {
 Console.WriteLine("No");
 }
 }
 }
Ето моето решение, но тестовете не ги смята вярно. От сума време си чукам главата и не мога да открия грешката: Някакви идеи? А да използвам и за едно странично въпросче- когато пресмятаме степен, има ли специален оператор или трябва да се ползва цикъл -в случая е квадрат и е лесно да се представи като умножение, но при по-големи степени...?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//Write an expression that checks for given point (x, y) if it is within the 
//circle K({1, 1}, 1.5) and out of the rectangle R(top=1, left=-1, width=6, height=2). 
    class CirclerectanglePoint
    {
        static void Main(string[] args)
        {
            double xK = 1;
            double yK = 1;
            double R = 1.5;
            
           for (int i = 1; i <= 10; i++)
            {
               Console.Write("x= ");
                double x = Convert.ToDouble(Console.ReadLine());
                    
                Console.Write("y= ");
                double y = Convert.ToDouble(Console.ReadLine());
                    
                bool InsideCircle;
                if (((x - xK) * (x - xK) + (y - yK) * (y - yK)) <= R * R)
                {
                    InsideCircle = true;
                }
                bool OutsideRectangle;
                if ((-1 > x && x > 5) && (-1 > y && y > 1))
                {
                    OutsideRectangle = true;
                }
                Console.WriteLine((InsideCircle = true) && (OutsideRectangle = true)? "yes" : "no"); 
              
            }
        }
  }
На въпросът ти за степента - има метод Math.Pow(double x, double y), който прави точно това - повдига дадено число на някаква степен. Разгледай го.
Имаш няколко грешки. Най-сериозната е когато принтираш на конзолата. Оператора = е оператор за присвояване. Така при принтирането винаги присвояваш на InsideCircle и OutsideRectangle true и съответно винаги получаваш като отговор yes. Оператора за сравнение е == Проверката при принтирането трябва да е:
Console.WriteLine((InsideCircle == true) && (OutsideRectangle == true)? "yes" : "no");
По подразбиране всяка една булева проверка проверява за true, така че може за по-кратко да го направиш:
Console.WriteLine(InsideCircle && OutsideRectangle ? "yes" : "no");
И понеже след като направиш тази промяна ще ти изкарва грешка, че InsideCircle и OutsideRectangle нямат стойност то трябва още при декларирането им да им присвояваш стойност:
bool InsideCircle = false;
bool OutsideRectangle = false;
И последната ти грешка е при проверката дали е извън правоъгълника. Ти си го направила:
if ((-1 > x && x > 5) && (-1 > y && y > 1)) , но така написано това условие никога няма да е true. Причината е, че си използвала && вместо ||. Няма как x да е едновременно < -1 и > 5, както и y няма как да е едновременно < -1 и > 1. Направи проверката така:
if (-1 > x || x > 5 || -1 > y || y > 1)
Да, грешката с && вместо || и аз я открих после. А преди да постна въпроса ми мина през ума и моментът с = и ==, но когато заменя равното с == ми подчертава променливите и излиза съобщение "Error 3 Use of unassigned local variable 'InsideCircle' " (съответно и за InsideRectangle). Променям само знака. Уж са ми декларирина променливите. Какво пропускам?
Здравейте, ето и моето решение. Сравнително кратко е:
using System;
class PointInCircleOutRectangle
{
 static void Main()
 {
 decimal x = decimal.Parse(Console.ReadLine());
 decimal y = decimal.Parse(Console.ReadLine());
 decimal r = 1.5M;
 bool inKoutR = ( ((x-1)*(x-1)) + ((y-1) * (y-1)) ) <= (r * r) && y > 1;
 Console.WriteLine(inKoutR ? "yes":"no");
 }
}
Я, още някой мисли като мене... :-)
Моят код е малко по-дълъг единствено с цел прегледност, но като алгоритъм е същият:
    class PointInCircleOutOfRectangle
    {
        static void Main()
        {
            Console.Write("x= ");
            double x = double.Parse(Console.ReadLine());
            Console.Write("y= ");
            double y = double.Parse(Console.ReadLine());
            double shadowX = x - 1;
            double shadowY = y - 1;
            double circleRadius = 1.5;
            double pointPosition = Math.Sqrt(shadowX * shadowX + shadowY * shadowY); // pointPosition defines the distance from the point to the center of the circle
            bool insideCircle = (pointPosition <= circleRadius);
            // Console.WriteLine(insideCircle);
            bool result = (pointPosition <= 1.5 && y > 1);
            Console.WriteLine("Is the point within the circle and out of the rectangle?");
            Console.WriteLine(result ? "Yes" : "No");
          
        }
    }