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

标签 c++

我正在编写一个程序,它从一个 .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/

相关文章:

c++ - Indy10 TCP 服务器卡住

c++ - 回调函数 C++

c++ - 使用 `&` 和 `(int*)` 打印 char* 有什么区别?

c++ - 有关初学者的数组和指针的问题

c++ - CryptDecrypt winapi 函数出错?

c++ - 如何检查 vector 中是否不存在元素?

c++ - 有没有在不使用CSS的情况下用c++编写的GTK + 3中多行文本字段的示例?

c++ - 无法解决使用 Ubuntu 构建 C++ 时的声明和循环错误

C++ const char* 到 char*

c++ - 在可能的情况下,C++ 是否总是更喜欢右值引用转换运算符而不是 const 左值引用?