简体   繁体   中英

How to fix code that is outputting 2 lines instead of one using if statements

My code compiles and when I run it and enter a number, then it will output 2 lines of code instead of one. I'm not sure if there is something wrong with my if-statement that is causing it. But I want to know what it causing my program to output 2 lines instead of 1 with if-statements?

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    double weight;

    cout << "Enter the weight of your package: ";
    cin >> weight;

    ofstream sout, mout, lout;
    sout.open("shiprates_small.txt");
    mout.open("shiprates_medium.txt");
    lout.open("shiprates_large.txt");

    if (sout.is_open())
    {
        if (weight >= 1 || weight < 10)
        {
            sout << "Shipping rates: " << endl;
            cout << "Go see shiprates_small.txt " << endl;
        }
        sout.close();
    }
    if (mout.is_open())
    {

        if (weight >= 10 || weight < 30)
        {
            mout << "Shipping rates: " << endl;
            cout << "Go see shiprates_medium.txt " << endl;
        }
        mout.close();
    }

    if (lout.is_open())
    {
        if (weight >= 30)
        {
            lout << "Shipping rates: " << endl;
            cout << "Go see shiprates_large.txt " << endl;
        }
        lout.close();
    }

    return 0;
}

This is the output

Enter the weight of your package: 9
Go see shiprates_small.txt
Go see shiprates_medium.txt

Replace the or || with and &&

if (weight >= 1 && weight < 10) {// der code}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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