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

时间:2019-06-08 09:58:16

标签: c++

我正在编写一个程序,该程序从.txt文件中获取一个“目标号码”和其他号码,并且需要编写一个新的.txt文件,该文件说明哪两个数字加起来就是目标号码。

我使用向量数组来获取文件中给出的所有数字。一个文件中的目标数量是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

1 个答案:

答案 0 :(得分:0)

由于其他所有功能都可以正常工作,因此只要找到第一组数字,就可以直接退出两个循环:

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