0

I have something which outputs all the factors for an integer using a fixed loop.

in this case, int_end_int_ = 4 and middle_x_coefficient = 4


for (int i = 1; i <= int_end_int_; i++)
    {
        if (int_end_int_ % i == 0) // This gets the factors
        {
            //here
        }
    }

i have that inside the if loop that if i * 2 == 4, print a string. So i thought that when i = 2, it will output the string.

//inside if loop
int newi = i * 2;
//i = 2
if (newi == middle_x_coefficient) {
    preroot1 = i; //ignore
    cout << "prerooted";
    preroot2 = i; //ignore
}

It does not output "prerooted", and i have no clue why.

Full Code:


#include <iostream>
#include <string>
using namespace std;

int main()
{
    cout << "Quadratic Equation Solver ( to roots )" << endl;
    cout << "Enter quadratic equation, e.x (x^2 + 4x + 4) must be in this form" << endl;

    string equation;
    cout << ">> ";
    getline(cin, equation);

    if (equation.length() < 12)
    {
        cout << "Please enter valid string." << endl;
        while (equation.length() < 12)
        {
            cout << ">> ";
            getline(cin, equation);
        }
    }

    char middle_x_coefficient = equation[6]; // getting x^2 + 4(this<-)x + 4
    char end_int_ = equation[11]; // getting  x^2 + 4x + 4 <-- this
    
    int preroot1 = 0;
    int preroot2 = 0;

    int int_end_int_ = static_cast<int>(end_int_); //convert char to int using static cast for like no reason
    //nvm <- https://stackoverflow.com/questions/103512/why-use-static-castintx-instead-of-intx this says it is better bc compiler bad or smthn
    int_end_int_ -= 48; //This converts the ascii value (52 for 4) to 4 (-48)

    int pasti = 0;
    
    for (int i = 1; i <= int_end_int_; i++)
    {
        if (int_end_int_ % i == 0)
        {
            cout << i << "this<- i" << endl;

            cout << middle_x_coefficient << "this<- x" << endl;

            
            int newi = i * 2;
            //i = 2
            if (newi == middle_x_coefficient) {
                preroot1 = i;
                cout << "prerooted";
                preroot2 = i;
            }
            else if (i + pasti == middle_x_coefficient) {
                preroot1 = i;
                preroot2 = pasti;
            }

            pasti = i;
        }
    }

    cout << preroot1 << " " << preroot2 << endl;
    return 0;
}

Kerch
  • 25
  • 6

1 Answers1

0

You converted the character end_int_ to the integer int_end_int_, but you didn't convert the character middle_x_coefficient to an integer. Convert and use converted integer just as you did for end_int_.

Instead of using magic number 48, using character literal '0' is better.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70