在数组中查找加起来给定数字c ++的数字

时间:2017-03-26 04:24:34

标签: c++ sum boolean

我正在编写这个代码,它接受输入文件并将该文件中的所有整数排序到一个数组中。然后它取用户选择的总和并通过所有组合(逐个/教授命令/)找到一个等于所需总和的对。一些代码很时髦,因为我们需要使用C ++ 03编译器-sigh-。该程序没有错误,但当我运行它时说

有1600张支票可以找到所需金额的产品

添加到您的总和的两个数字是40和40 分段错误(核心转储)

(所需的金额不是可以在输入文件中找到的金额,因此它应该说“程序没有找到任何匹配。再试一次。”)

代码非常混乱,我很抱歉,但是我花了好几个小时搬东西,添加新东西或尝试新的东西尝试使它工作。

我感觉这是一个问题,我如何声明布尔变量,或者我如何传递它们。

int x, i, n1, n2, pos1 = 0, pos2 = 0,accesses = 0;
bool fail = false;

int readSortedArray (int array[20], int count, istream& infile)
{   
count = 0;
while(infile >> array[count])
{
    count++;

}

return count;
}

int findproducts (int array[20], int& n1, int& n2, int count, int sum, int& accesses, bool fail, istream& infile)
{   
bool found = true;
while(found == true)
{
for( i = 0; i < count; i++)
{
pos1++;
n1 = array[i];
pos2 = 0;
for( x = 0; x < count; x++)
{
pos2++; accesses ++;
n2 = array[x]; 
if(sum == n1 + n2)
{
    found = false;
    fail = false;
}
if(sum != n1 + n2)
{
    fail = true;
}
}
}
}

return fail;
}

int main ()
{
 int array[20];
 int answer, sum, count = 0;

std::string input_filename;
ifstream infile;

cout << "Please enter name of the input file: ";
cin >> input_filename;
infile.open(input_filename.c_str());
if (!infile)
{
    cout << "Could not open input file one\n";
    return 0;
}

cout << "Please enter the prefered sum ";
cin >> sum;

count = readSortedArray(array, count, infile); 

fail = findproducts(array, n1, n2, count, sum, accesses, fail, infile);

cout << "There were " << accesses << " checks made to find the products of your desired sum and" << endl;

if(fail == true)
{
    cout << " the program did not find any matches. try again. ";
}
if(fail == false)
{
cout << endl << "the two numbers that add to your sum are " << n1 << " and " << n2 << endl << ". These were found in position " << pos1 << " and " << pos2;
}

 return 0;
}

2 个答案:

答案 0 :(得分:1)

我收录了Karan S Warraich关于bool类型的评论。我还将文件参数删除到findProducts。但最重要的问题是while循环在没有找到任何东西的情况下永远运行。我摆脱了它。此外,重要的是在好的数字再次丢失并且失败被重置之前退出。正如您所指出的那样,可以进行大量的代码清理(比如现在发现什么都不做,并且无需在findproducts中设置失败),但这里有一些有用的东西

bool findproducts (int array[20], int& n1, int& n2, int count, int sum, int& accesses, bool fail)
{   
bool found = true;
for( i = 0; i < count; i++)
{
    pos1++;
    n1 = array[i];
    pos2 = 0;
    for( x = 0; x < count; x++)

        {
        pos2++; accesses++;
        n2 = array[x]; 
        if(sum == n1 + n2)
        {
        found = false;
        fail = false;
        return false;
        }

        }
}

return true;
}

答案 1 :(得分:0)

在你的findproduct函数中你返回bool值,而你的函数是int类型,要么使你的函数成为bool返回类型,要么返回1表示true,0表示false