gpt4 book ai didi

c++ - 在数组中查找加起来等于给定数字的数字 C++

转载 作者:行者123 更新时间:2023-11-28 05:13:58 24 4
gpt4 key购买 nike

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

进行了 1600 次检查以找到您想要的总和的产品

相加的两个数字是 40 和 40段错误(核心转储)

(所需的总和无法在输入文件中找到,因此它应该说“程序未找到任何匹配项。再试一次。”)

代码非常困惑,我很抱歉,但我花了几个小时来移动东西并添加新东西或尝试一些新东西来尝试让它工作。

我感觉我声明 boolean 变量的方式或传递它们的方式有问题。

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

最佳答案

我合并了 Karan S Warraich 关于 bool 类型的评论。我还删除了 findProducts 的文件参数。但最大的问题是 while 循环在找不到任何东西时永远运行。我摆脱了它。此外,重要的是在好的数字再次丢失和失败被重置之前退出 for 。正如您所注意到的,许多代码清理是可能的(比如 found now 什么都不做,并且 fail 不需要在 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;
}

关于c++ - 在数组中查找加起来等于给定数字的数字 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43024970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com