简体   繁体   中英

Run-Time Calculation

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 .

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM