gpt4 book ai didi

c++ - 如何在跳过已经添加的数字的同时在数组中添加数字?

转载 作者:太空宇宙 更新时间:2023-11-04 12:35:38 27 4
gpt4 key购买 nike

我正在编写一个程序,它从一个 .txt 文件中获取一个“目标数字”和其他数字,并且需要编写一个新的 .txt 文件来说明哪两个数字之和等于目标数字。

我使用 vector 数组来接收他们提供的文件中的所有数字。一个文件中的目标数字是 13,我需要确定它是否可以加起来为 13 的数字是 5 12 8 10 7 4 3 5 5 3 2 1。我已经设法让程序运行,但是如您所见,数字列表有多个“5”,因此它会多次重复“8 + 5 = 13”“5 + 8 = 13”。

vector<int> numbers;
int currentInt;
while (inFile >> currentInt) {
numbers.push_back(currentInt);
}
int length = numbers.size();
outfile << target << endl;
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
if (numbers[i] + numbers[j] == target) {
outFile << "Yes" << endl;
if (i == j) {
outFile << numbers[i] << "*2=" << target << endl;
}
else {
outFile << numbers[i] << "+" << numbers[j] << "=" << target << endl;
}
}
}
}
cout << "The new created file will contain the doubles and sums leading to the target number" << endl;
inFile.close();
outFile.close();
return 0;
}

预期的输出应该是:

13                        // the target number
5 12 8 10 7 4 3 5 5 3 2 1 // the numbers that can sum up to 13
Yes // declaring that there are 2 numbers that add up to 13
5+8=13 // saying which numbers add up to 13

对我来说输出什么:

13
Yes
5+8=13
Yes
12+1=13
Yes
8+5=13
Yes
8+5=13
Yes
8+5=13
Yes
10+3=13
Yes
10+3=13
Yes
3+10=13
Yes
5+8=13
Yes
5+8=13
Yes
3+10=13
Yes
1+12=13

最佳答案

由于其他一切正常,您可以在找到第一组数字后立即退出两个 for 循环:

vector<int> numbers;
int currentInt;
while (inFile >> currentInt) {
numbers.push_back(currentInt);
}
int length = numbers.size();
outfile << target << endl;

bool done = false;
for (int i = 0; i < length && !done; i++) {
for (int j = 0; j < length; j++) {
if (numbers[i] + numbers[j] == target) {
outFile << "Yes" << endl;
if (i == j) {
outFile << numbers[i] << "*2=" << target << endl;
}
else {
outFile << numbers[i] << "+" << numbers[j] << "=" << target << endl;
}

done = true;
break;
}
}
}
cout << "The new created file will contain the doubles and sums leading to the target number" << endl;
inFile.close();
outFile.close();
return 0;
}

关于c++ - 如何在跳过已经添加的数字的同时在数组中添加数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56505304/

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