2012-12-11 66 views
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,而不是正向反向。

在此先感謝您的幫助。

+0

如何只生成他們都在開始?所有的消極和postivies? – Annabelle

回答

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

感謝這工作,我感謝幫助。 :) –