Run-Time Calculation - c#

i am working on Windows Forms Application. i have three buttons. i have written a method that calculates a new location for each button. but i had some errors (explained after the code). the method is:
Random random = new Random();
public int SetPointLocation()
{
int x1 = x2 - 20;
int x2;
int x3 = x2 + 20;
int y1 = y2 - 1;
int y2 = random.Next(0, 2);
int y3 = y2 + 1;
return x2 = (((x3 - x1) * (y2 - y1)) / y3 - y1) + x1;
}
the errors i get :
Cannot use local variable 'x2' before it is declared.
Cannot use local variable 'y2' before it is declared.
so i rearranged the method's block:
Random random = new Random();
public int SetPointLocation()
{
int x2;
int x1 = x2 - 20;
int x3 = x2 + 20;
int y2 = Convert.ToInt32((picBox.Name).Remove(0, 10));
int y1 = y2 - 1;
int y3 = y2 + 1;
return x2 = (((x3 - x1) * (y2 - y1)) / y3 - y1) + x1;
}
now the errors i get:
"Use of unassigned local variable 'x2'".
The formula i've used is the way of finding the median from a Frequency tables "Statistics".
but 'x2' is unknown and i want to calculate it at run-time, but because 'x2' has no value, i can't set 'x1', and 'x3'. What is the solution for this problem?!

Simply use
int x2 = 0;
Everything needs to be initialized before it can be used. This is a requirement of the language.
Not too close related, but hits it anyways: SO.

It sounds like you really just want to pass x2 in as a parameter. You can then call the function when you do know what x2 is supose to be.
Random random = new Random();
public int SetPointLocation(int x2)
{
int x1 = x2 - 20;
int x3 = x2 + 20;
int y2 = Convert.ToInt32((picBox.Name).Remove(0, 10));
int y1 = y2 - 1;
int y3 = y2 + 1;
// Just return what x2 needs to be
return (((x3 - x1) * (y2 - y1)) / y3 - y1) + x1;
}

x2 is not set before using it.
Random random = new Random();
public int SetPointLocation()
{
int x2; // <- here' the problem
int x1 = x2 - 20;
...
give a value to x2:
x2 = 123;
using a uninitialized variable is not allowed in C#.
the compiler should tell you the place where the error is.

Related

Random Walker loop issue for C#

I am working on a simple Random Walker program that should draw a 10p long line, then choose a random cardinal direction to draw another line (also 10p long) until a certain number of lines have been reached.
I am using four coordinates to draw the line (two coordinates for X and two for Y). The Y coordinates are pushed into a Stack after every line is drawn and they are popped out as the X coordinates. This should ensure that the starting point of every second line is the end-point of the previous line.
The program draws on a Windows Form after pushing a Button controller. As of now, the output is something like this:
This here is my event handler code block for the button:
// Graphics and Pen classes instantiated
Graphics graphics;
graphics = this.CreateGraphics();
Pen pen = new Pen(Color.Black);
pen.Width = 1;
// lineLength is 10 pixels
// gridLength and gridWidth are needed to keep the Random Path inside a 600×600 field (this is not yet implemented in the code)
// lineCount is for maximizing the number of lines to be drawn and to control the loop
int lineLength = 10;
int gridWidth = 600;
int gridLength = 600;
int lineCount = 0;
// Starting line drawn with the following coordinates:
int x1 = 20;
int x2 = 20;
int y1 = 20;
int y2 = 30;
graphics.DrawLine(pen, x1, y1, x2, y2);
lineCount++;
// Stack initialized to store "y" coordinates
// "y" coordinates should be passed on as "x" coordinates for every consecutive lines
// so that the ending point's coordinate of a line
Stack<int> stackY = new Stack<int>();
stackY.Push(y2);
stackY.Push(y1);
for (lineCount = 1; lineCount <= 64; lineCount++)
{
// X pops current Y coordinates from stack
x1 = stackY.Pop();
x2 = stackY.Pop();
// Initializing the random number (between 1 and 4) generator to choose from the cardinal directions
Random rnd = new Random();
int dir = rnd.Next(1, 5);
switch (dir)
{
// up
case 1:
y1 = y1 + lineLength; // y1 plus lineLength
graphics.DrawLine(pen, x1, y1, x2, y2); //drawing the line
stackY.Push(y2); // pushing the current y coordinates into the stack
stackY.Push(y1);
break;
// right
case 2:
y1 = y2 + lineLength; // y2 plus lineLength
graphics.DrawLine(pen, x1, y1, x2, y2);
stackY.Push(y2);
stackY.Push(y1);
break;
// down
case 3:
y1 = y1 - lineLength; // y1 minus lineLength
graphics.DrawLine(pen, x1, y1, x2, y2);
stackY.Push(y2);
stackY.Push(y1);
break;
// left
case 4:
y2 = y2 - lineLength; // y2 minus lineLength
graphics.DrawLine(pen, x1, y1, x2, y2);
stackY.Push(y2);
stackY.Push(y1);
break;
} //switch
} //for
} //event handler
I am not really sure what went wrong - I appreciate any heads-up and advices! Thank you!
You are making this far more complicated than you need to. Also you are mixing the x and y coordinates in a way that doesn't make sense.
You don't need a stack, just store the most recent points. Something like this.
int x = 20, y = 20;
int new_x = x, new_y = y;
Random rnd = new Random();
for (int i = 0; i < numLines; i++)
{
int dir = rnd.Next(1, 5);
if (dir == 1) new_x += lineLength;
if (dir == 2) new_x -= lineLength;
if (dir == 3) new_y += lineLength;
if (dir == 4) new_y -= lineLength;
graphics.DrawLine(pen, x, y, new_x, new_y);
x = new_x;
y = new_y;
}
Also you don't need to redeclare the Random object every time, just once before the loop.

Quadratic equation calculator not working

I would like some help with my code.
This is what I've done so far:
using System;
namespace quadratic_equcation
{
class Program
{
static void Main(string[] args)
{
float a = float.Parse(Console.ReadLine());
float b = float.Parse(Console.ReadLine());
float c = float.Parse(Console.ReadLine());
float D = b * b - 4 * (a * c);
double dRoot = Math.Sqrt(D);
double x1 = (-b + dRoot) / 2 * a;
double x2 = (-b + dRoot) / 2 * a;
Console.WriteLine("x1 = {0) x2 = {1}", x1, x2);
Console.ReadLine();
}
}
}
Everything looks good. I got no errors but when I run it I get this error:
How can I fix it ?
And one more question. I couldn't use float with 'dRoot', 'x1' and 'x2' because I can't convert it from double to float.. How can i do this
Console.WriteLine("x1 = {0) x2 = {1}", x1, x2);
you have a typo there... {0)
change it for
Console.WriteLine("x1 = {0} x2 = {1}", x1, x2);
PS: the roots signs are faulty too (one positive one negative)
double x1 = (-b + dRoot) / 2 * a;
double x2 = (-b - dRoot) / 2 * a;
You have typo: {0) in format string.
Console.WriteLine("x1 = {0} x2 = {1}", x1, x2);
Moreover, you have error in algorithm: x1 is same as x2.
double x1 = (-b + dRoot) / 2 * a;
double x2 = (-b - dRoot) / 2 * a;

Iteration of an Unknown Number in C#

Let's say I have a formula which contains a variable that user has to guess. But at the end of formula, that variable is calculated again and if the first one and second one doesn't match, formulation has to be solved again with a new value. Shortly assume that I have a formula like this (mine is much more complex and longer than this);
double y1 = Convert.ToDouble(txtboxPredefinedY.Text);
double x, z, Ort;
double y2 = 0;
while (y1 != y2)
{
x = (Math.Pow(y1, 2)) + 10;
z = (y1 - 2) / 3;
y2 = (x / z);
Ort = (y2 + y1)/2;
y1 = Ort;
if (y1 == y2)
break;
}
txtboxResult.Text = r.ToString();
So the y1 variable I defined first has to match the last variable y2. To achieve this I calculate the whole formula and find a new y1, re-calculate formula.
I want to define a y1 value and let the application correct me. For example this code should return me a value of 3.3158. If first input is 3.3158 than y1 becomes equal to y2.
I couldn't use while iteration correctly. How can I fix this? Or maybe, how should I build my while block to give me exact equation?
When working with Double you should compare with tolerance:
double y1 = Convert.ToDouble(txtboxPredefinedY.Text);
double x, z, Ort;
double y2 = 0;
double tolerance = 0.001;
while (Math.Abs(y1 - y2) >= tolerance) {
x = (Math.Pow(y1, 2)) + 10;
z = (y1 - 2) / 3;
y2 = (x / z);
Ort = (y2 + y1)/2;
y1 = Ort;
}
Comparisons like y1 != y2 as well as y1 == y2 may fail because of round-up errors.

Value of expression doesn't change

I'm trying to move the cursor using linear interpolation. My problem is that the value of y0 + (y1 - y0) * ((x - x0) / (x1 - x0)) never changes despite the fact that x changes. I can't figure out what I'm missing.
public void MoveCursor(int x1, int y1)
{
int y, y0, x, x0;
y0 = Cursor.Position.Y;
x0 = Cursor.Position.X;
for (x = x0; x > x1; x--)
{
y = y0 + (y1 - y0) * ((x - x0) / (x1 - x0));
this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(x,y);
Cursor.Clip = new Rectangle(this.Location, this.Size);
Console.Out.WriteLine("X:{0} Y:{1}", x, y);
System.Threading.Thread.Sleep(100);
}
}
Try using floats:
y = (int)(y0 + (float)(y1 - y0) * (x - x0) / (x1 - x0));

Drawing on a canvas a big pixels

I am writing an app which allow user to draw on a touch screen display. I am currently using the method below and it work very well. This method is producing a “high resolution image” since for almost every single pixel a line is drawn (e.g. 100, 100 -> 102, 103).
Here is my question. I’d like user to draw a “low resolution picture” (big pixels board) where you can intentionally see pixels of 50×50 (e.g. 100, 100 -> 150, 150). Does anybody have an idea on how to accomplish that? I am using Silverlight for Windows Phone. I was thinking about building a big grid of 50×50 pixels, but there might be too many controls.
void FingerMove(object sender, MouseEventArgs e)
{
if (this.IsDrawing)
{
this.DestinationPoint = e.GetPosition(paint);
Line line = new Line
{
Stroke = this.Color,
X1 = this.DestinationPoint.X,
Y1 = this.DestinationPoint.Y,
X2 = this.OriginPoint.X,
Y2 = this.OriginPoint.Y,
StrokeStartLineCap = PenLineCap.Round,
StrokeEndLineCap = PenLineCap.Round,
StrokeThickness = 15,
Opacity = 1,
};
Debug.WriteLine(string.Join(",", line.X1, line.Y1, line.X2, line.Y2));
paint.Children.Add(line);
}
this.OriginPoint = this.DestinationPoint;
}
#Amr has the right idea. I'll give you this code with the caveat that I haven't tested it at all. I took the line segment intersection algorithm from here.
First, you need to set up a list of Rectangles and add them to the canvas that are your "pixels":
private List<Rectangle> _rects = new List<Rectangle>();
private void GenerateRects()
{
int width = 300; // or whatever dimensions...
int height = 300;
int gridSize = 50;
for (int x = 0; x < width; x += gridSize)
{
for (int y = 0; y < height; y += gridSize)
{
var rect = new Rectangle
{
Opacity = 0,
Width = Math.Min(gridSize, width - x),
Height = Math.Min(gridSize, height - y),
};
Canvas.SetLeft(rect, x);
Canvas.SetTop(rect, y);
_rects.Add(rect);
this.paint.Children.Add(rect);
}
}
}
We'll need these helper methods:
class LineSegment
{
public double X1 { get; set; }
public double X2 { get; set; }
public double Y1 { get; set; }
public double Y2 { get; set; }
}
private static bool SegmentsIntersect(LineSegment A, LineSegment B)
{
double x1 = A.X1, x2 = A.X2, x3 = B.X1, x4 = B.X2;
double y1 = A.Y1, y2 = A.Y2, y3 = B.Y1, y4 = B.Y2;
double denominator = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
if (denominator == 0)
return false;
double ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denominator;
double ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denominator;
return (ua > 0 && ua < 1 && ub > 0 && ub < 1);
}
private static bool RectIntersectsLine(Rect A, LineSegment B)
{
return (SegmentsIntersect(B, new LineSegment { X1 = A.X, Y1 = A.Y, X2 = A.X, Y2 = A.Y + A.Height }) ||
SegmentsIntersect(B, new LineSegment { X1 = A.X, Y1 = A.Y + A.Height, X2 = A.X + A.Width, Y2 = A.Y + A.Height }) ||
SegmentsIntersect(B, new LineSegment { X1 = A.X + A.Width, Y1 = A.Y + A.Height, X2 = A.X + A.Width, Y2 = A.Y }) ||
SegmentsIntersect(B, new LineSegment { X1 = A.X + A.Width, Y1 = A.Y, X2 = A.X, Y2 = A.Y }) ||
RectContainsPoint(A, new Point(B.X1, B.Y1)) ||
RectContainsPoint(A, new Point(B.X2, B.Y2)));
}
private static bool RectContainsPoint(Rect A, Point B)
{
return (B.X > A.X && B.X < A.X + A.Width && B.Y > A.Y && B.Y < A.Y + A.Height);
}
Then, in the FingerMove function, we loop through each Rectangle to see if it intersects. If it does, we change its color:
void FingerMove(object sender, MouseEventArgs e)
{
if (this.IsDrawing)
{
this.DestinationPoint = e.GetPosition(paint);
LineSegment line = new LineSegment
{
X1 = this.DestinationPoint.X,
Y1 = this.DestinationPoint.Y,
X2 = this.OriginPoint.X,
Y2 = this.OriginPoint.Y
};
foreach (var rect in _rects)
{
var x = Canvas.GetLeft(rect);
var y = Canvas.GetTop(rect);
if (RectIntersectsLine(new Rect(x, y, rect.Width, rect.Height) , line))
{
rect.Opacity = 1;
rect.Fill = Color;
}
}
}
this.OriginPoint = this.DestinationPoint;
}
If you simply want to make the line thicker, just experiment with possible values of StrokeThickness untill you get the desired effect.
If you want to manually draw the line by filling up large areas of the screen say (50x50) rectangles, you could do the follwing:
divide the screen into 50x50 rectangles
check which rectangles are intersected by the line drawn by the user
only draw the rectangles from step 2
This would give you the 'snap to grid' line that you want.

Categories