How to have C++ solve the equation for an input value?

前端 未结 4 1552
Happy的楠姐
Happy的楠姐 2021-01-29 08:06

I am stuck trying to figure out a way using C++ to solve a situation where the user inputs a value using cin and then have the computer solve for a way to get the value of cin,

4条回答
  •  太阳男子
    2021-01-29 08:13

    This case can be solved trivially by interval arithmetic. C++ code that solves your "sum of two interval-constrained variables problem" is given below.

    int min_x = 30, max_x = 50;
    int min_y = 60, max_y = 90;
    
    // solutions exist in this interval
    int min_z = min_x + min_y, max_z = max_x + max_y;
    
    cin >> input;
    
    // solutions possible?
    if (input >= min_z && input <= max_z)
    {
        // determine solution interval for x (y is dependent)
        cout
        << "Solution:\n"
        << "x in [" << min(max(  input - max_y  , min_x),max_x)
        << ";"      << min(max(  input - min_y  , min_x),max_x) << "], "
        << "y = "   << input << " - x" << endl;
    }
    else
    {
        cout << "No solution." << endl;
    }
    

    Computers are "basically stupid" and if they do smart things it is the software. Using a general purpose programming language like C++ requires you (or at least the libraries you eventually use) to be very specific on how exactly to solve a problem based on the simple arithmetic means of the bare computer.

    Although the programming language won't magically and somehow do things for you, algorithms exist to solve many mathematical standard problems such as e.g. systems of equations. Numerical Recipes in C++ covers a variety of algorithms and their C++ implementations.

提交回复
热议问题