0

タイトルの長さで説明する方法がよくわからないため、タイトルでこれをうまく説明できなかった可能性があるため、お詫び申し上げます。とにかく、これは私の現在のコードです:

// Gets the product that is used to get the factors
cout << "Enter a number that you want to be factored" << endl;
cin >> y;

system("cls");

// Gets the sum from the user that the two factors need to add up to
cout << "Input the sum that is needed" << endl;
cin >> neededSum;

secondary = y;
system("cls");

// Lists the factors that add up to the specified sum
cout << "The numbers that add up to " << neededSum << " are:" << endl;
for (int i = 0; i < 100; i++)
{
    x++;
    increment++;
    y = secondary / x;
    product = x * y;
    if (product == secondary)
    {
        sum = x + y;
        if (sum == neededSum)
        {
            cout << x << " and " << y << endl;
        }
    }
}

基本的に、製品にはその製品のすべての要素がリストされています。次に、合計が指定された合計になるものが見つかるまで、すべての要素を合計します。

ただし、指定された合計がたとえば「-11」のように負の場合、「28」(例) の係数は -4 と -7 ではなく 4 と 7 であるため、機能しません。これを修正する方法を見つけて、正の逆ではなく -4 と -7 でなければならない場合を認識できるようにする必要があります。

助けてくれてありがとう。

4

1 に答える 1

2

x と y が負であると仮定してください:

if (product == secondary)
{
    sum = x + y;
    if (sum == neededSum)
    {
        cout << x << " and " << y << endl;
    }
    else if (-sum == neededSum)
    {
        cout << -x << " and " << -y << endl;
    }
}
于 2012-12-11T02:28:37.377 に答える