简体   繁体   English

布尔语句 C++

[英]Boolean statements c++

I am creating a program that compares all the values of an array and reads which values add up to the desired sum.我正在创建一个程序来比较数组的所有值并读取哪些值加起来为所需的总和。 If there aren't any values that add up to the desired sum, it should output a statement saying No matching sum was found, this is the part I'm having issues with.如果没有任何值加起来达到所需的总和,它应该输出一条语句,说没有找到匹配的总和,这是我遇到问题的部分。 I should specify what it outputs.我应该指定它输出什么。 At the moment every time there isn't a match it prints "no matching sum was found" so It creates quite the messy output目前,每次没有匹配项时,它都会打印“未找到匹配的总和”,因此会产生相当混乱的输出

using namespace std;

const int SIZE = 15;
int intArray[SIZE];

void readData(istream& inFile) {
    for (int i = 0; i < SIZE; i++){
        inFile >> intArray[i];
        cout << intArray[i] << " ";
    }
}

int main() {
    int sum;
    ifstream inFile;
    string inFileName = "inFile.txt";
    inFile.open(inFileName.c_str());

    readData(inFile);
    
    cout << "Please enter the number for which a matching sum is needed: ";
    cin >> sum;
    bool error = true;
    for(int i = 0; i <= SIZE; i++){
        for(int j = 1; j <= SIZE; j++){
            if((intArray[i] + intArray[j]) == sum){
                cout << "Item " << i << " (With value " << intArray[i] << ") " << "and item " << j << " (With value " << intArray[j] << ") add up to " << sum << endl;
                error = false;
            }
        }
    }
    if(error == true){
        cout << "No matching sum was found" << endl;
    }
    return 0;
}

The quick fix to your question is below.您的问题的快速解决方法如下。

for(int i = 0; i < SIZE; i++){
    for(int j = i+1; j < SIZE; j++){
        if((intArray[i] + intArray[j]) == sum){
            cout << "Item " << i << " (With value " << intArray[i] << ") " << "and item " << j << " (With value " << intArray[j] << ") add up to " << sum << endl;
            error = false;
        }
    }
}

Please be noted that:请注意:

  1. You are reading an array of "SIZE" but looping across for SIZE+1 times, starting from 0 to SIZE您正在读取“SIZE”数组,但从 0 到 SIZE 循环遍历 SIZE+1 次
  2. You are starting j loop from 1, which is an inefficient way.您从 1 开始 j 循环,这是一种低效的方式。 You can start the loop with i+1, as there is no possibility by which matching pairs would escape the notice of this loop.您可以用 i+1 开始循环,因为匹配对不可能逃脱此循环的注意。

Let me know if this fixes your issue.如果这能解决您的问题,请告诉我。 Happy Coding!快乐编码!

You have a minor problem in your function, where you iterate over the bounds of your array.你的函数有一个小问题,你在数组的边界上迭代。 In C++ arrays start at index 0. And therefore, the last element index is the array-size minus 1.在 C++ 中,数组从索引 0 开始。因此,最后一个元素索引是数组大小减 1。

Example: Array with five elements示例:包含五个元素的数组

int array[5] = {10,20,30,40,50};
  • array at index 0 (array[0]) = 10索引 0 处的数组 (array[0]) = 10
  • array at index 1 (array[1]) = 20索引 1 处的数组 (array[1]) = 20
  • array at index 2 (array[2]) = 30索引 2 处的数组 (array[2]) = 30
  • array at index 3 (array[3]) = 40索引 3 处的数组 (array[3]) = 40
  • array at index 4 (array[4]) = 50索引 4 处的数组 (array[4]) = 50

And, if you want to iterate over the array in a loop, then, with the size 5, you need to write:而且,如果你想在一个循环中遍历数组,那么,大小为 5,你需要写:

for (int i = 0; i < 5; ++i)

So, for this case, always < , not <= .所以,对于这种情况,总是< ,而不是<=

If you run your program you will notice that you get somehow double results, so, you may get index 3 and 5, and index 5 and 3. You may even get a double, same index, if the sum given by the user is double than a value in an array.如果你运行你的程序,你会注意到你得到了双倍的结果,所以,你可能会得到索引 3 和 5,以及索引 5 和 3。如果用户给出的总和是双倍,你甚至可能得到双倍的相同索引比数组中的值。 Example: if you have the value 4 in you array, and are looking for the sum 8, your program will give you the value 4 with the same index.示例:如果您的数组中有值 4,并且正在寻找总和 8,您的程序将为您提供具有相同索引的值 4。

So, you need to understand your requirements for the results所以,你需要了解你对结果的要求

  • If you want to get ordered pairs, then: For the sum 10, the pair 3,7 and 7,3 are different.如果你想得到有序对,那么: 对于和 10,对 3,7 和 7,3 是不同的。 In that case you need to start both loop indices from 0在这种情况下,您需要从 0 开始两个循环索引
  • If you want to avoid one element being double, like for sum 8 and one element 4, then getting pair 4,4., you need to add an additional if -statement, like if (i != j) .如果你想避免一个元素是双倍的,比如和 8 和一个元素 4,然后得到对 4,4.,你需要添加一个额外的if语句,比如if (i != j)
  • If not-ordered pairs are desired, meaning, we do not want to see 3,7 and 7,3 then you need to start your second loop at index i+1.如果需要无序对,这意味着我们不想看到 3,7 和 7,3,那么您需要在索引 i+1 处开始第二个循环。

Then, next, some optimization.然后,接下来,一些优化。 You may notice that the term intArray[i] is invariant.您可能会注意到术语intArray[i]是不变的。 It will never change.它永远不会改变。 So, you can take it out of the inner loop and shift it to the outer loop.因此,您可以将其从内循环中取出并将其移至外循环。 And additionally, you perform always the same addition.此外,您始终执行相同的加法。 That is basically not necessary.那基本上是没有必要的。 You can rewrite:你可以重写:

intArray[i] + intArray[j] == sum      to
intArray[j]) == sum - intArray[i]

And if we replace the term sum- intArray[i] with delta , then we can optimize our loops to:如果我们用delta替换术语sum- intArray[i] ,那么我们可以优化我们的循环:

    bool error = true;
    for (int i = 0; i < SIZE; i++) {
        const int delta = sum - intArray[i];

        for (int j = i+1; j < SIZE; j++) {

            if (intArray[j] == delta) {
                cout << "Item " << i << " (With value " << intArray[i] << ") " << "and item " << j << " (With value " << intArray[j] << ") add up to " << sum << endl;
                error = false;
            }
        }
    }

We have now only one subtraction (instead of multiple additions), access the intArray[i] only once and make only comparisons in the inner loop.我们现在只有一次减法(而不是多次加法),只访问intArray[i]一次并且只在内循环中进行比较。

Then we can generally improve the code and use more modern C++ elements.然后我们通常可以改进代码并使用更现代的 C++ 元素。 We need to add error checking for user input and define variables, when we need them and not before.我们需要为用户输入添加错误检查并定义变量,当我们需要它们时而不是之前。

#include <iostream>
#include <fstream>
#include <vector>

int main() {

    // First open source file and check, if it could be opened
    // If we cannot open it then no need to do something else
    if (std::ifstream inFileStream{"r:\\inFile.txt"}; inFileStream) {

        // Instructions for the user
        std::cout << "\nPlease enter the number for which a matching sum is needed: ";

        // Get the required sum and check for a correct input
        if (int requiredSum{}; std::cin >> requiredSum) {

            // Now, the indicator that shows, if we could find a pair or not
            bool matchingPairFound{};
            // Container for data
            std::vector<int> data{};

            // Read next value from source file until end of file and store it
            for (int i{}, value{}; inFileStream >> value; i++) {

                data.push_back(value);

                // Delta value to find
                const int delta = requiredSum - value;

                for (int j = i - 1; j >= 0; --j) {
                    if (delta == data[j]) {

                        // We found a match
                        matchingPairFound = true;
                        // Show somedebug output
                        std::cout << "Item " << i << " (With value " << data[i] << ") " << "and item " << j << " (With value " << data[j] << ") add up to " << requiredSum << '\n';
                    }
                }
            }
            std::cout << "\nMatching sum was " << (matchingPairFound ? "found" : "not found") << '\n';
        }
        else std::cerr << "\n\n***Error: Could not read sum value\n\n";
    }
    else std::cerr << "\n\n***Error: Could not open input file\n\n";

    return 0;
}

That is not the end.那不是结束。 If the requirement is that we just want to know if there is a pair adding up to a sum, we do not need to read all values.如果要求是我们只想知道是否有一对加起来为和,我们不需要读取所有值。 We will read value by value and then stop as soon as we have a result.我们将逐个读取值,然后在获得结果后立即停止。 The loops will then run backward然后循环将向后运行

#include <iostream>
#include <fstream>
#include <vector>

int main() {

    // First open source file and check, if it could be opened
    // If we cannot open it then no need to do something else
    if (std::ifstream inFileStream{"r:\\inFile.txt"}; inFileStream) {

        // Instructions for the user
        std::cout << "\nPlease enter the number for which a matching sum is needed: ";

        // Get the required sum and check for a correct input
        if (int requiredSum{}; std::cin >> requiredSum) {

            // Now, the indicator that shows, if we could find a pair or not
            bool matchingPairFound{};
            // Container for data
            std::vector<int> data{};

            // Read next value from source file until end of file and store it
            for (int i{}, value{}; (inFileStream >> value) and not matchingPairFound; i++) {

                data.push_back(value);

                // Delta value to find
                const int delta = requiredSum - value;

                for (int j = i - 1; (j >= 0) and not matchingPairFound; --j) {
                    if (delta == data[j]) {

                        // We found a match
                        matchingPairFound = true;
                        // Show somedebug output
                        std::cout << "Item " << i << " (With value " << data[i] << ") " << "and item " << j << " (With value " << data[j] << ") add up to " << requiredSum << '\n';
                    }
                }
            }
            std::cout << "\nMatching sum was " << (matchingPairFound ? "found" : "not found") << '\n';
        }
        else std::cerr << "\n\n***Error: Could not read sum value\n\n";
    }
    else std::cerr << "\n\n***Error: Could not open input file\n\n";

    return 0;
}

And, if we want not to see content of the pair and not the indices, the program will be even more compact.而且,如果我们不想看到对的内容而不是索引,程序将更加紧凑。 We assumed unordered pairs as the result.我们假设无序对作为结果。 And we do not care for duplicates in source input file.我们不关心源输入文件中的重复项。 They will not add any value.他们不会增加任何价值。 There is a good container available for that purposes.有一个很好的容器可用于此目的。 It is the std::unordered_set which will only store unique values and use a fast hash algorithm to access the data. std::unordered_set只会存储唯一值并使用快速哈希算法来访问数据。

The below code下面的代码

  • Reads any number of data from the input file从输入文件中读取任意数量的数据
  • Reads only as long as no decision could be made仅在无法做出决定时读取
  • Stores only distinct values until a decision can be made仅存储不同的值,直到做出决定
  • Is with that size and speed optimized具有优化的大小和速度
  • And is compact.而且很紧凑。 Only 10 lines of code in function main函数main只有 10 行代码
#include <iostream>
#include <fstream>
#include <vector>
#include <unordered_set>

int main() {

    // First open source file and check, if it could be opened
    // If we cannot open it then no need to do something else
    if (std::ifstream inFileStream{"r:\\inFile.txt"}; inFileStream) {

        // Instructions for the user
        std::cout << "\nPlease enter the number for which a matching sum is needed: ";

        // Get the required sum and check for a correct input
        if (int requiredSum{}; std::cin >> requiredSum) {

            // Now, the indicator that shows, if we could find a pair or not
            bool matchingPairFound{};

            // Container for data
            std::unordered_set<int> alreadySeenData{};

            // Read values from input file until End-Of-File or until a matching pair was found
            for (int value{}; (inFileStream >> value) and not matchingPairFound; alreadySeenData.insert(value)) {

                // Check, if matching pair was found
                matchingPairFound = (alreadySeenData.count(requiredSum - value));
            }
            // Show result
            std::cout << "\nMatching sum was " << (matchingPairFound ? "found" : "not found") << '\n';
        }
        else std::cerr << "\n\n***Error: Could not read sum value\n\n";
    }
    else std::cerr << "\n\n***Error: Could not open input file\n\n";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM