如何使用 if 语句修复输出 2 行而不是 1 行的代码
How to fix code that is outputting 2 lines instead of one using if statements
我的代码可以编译,当我 运行 它并输入一个数字时,它会输出 2 行代码而不是一行。我不确定我的 if 语句是否有问题导致它。但我想知道是什么导致我的程序输出 2 行而不是 1 行 if 语句?
#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;
}
这是输出
Enter the weight of your package: 9
Go see shiprates_small.txt
Go see shiprates_medium.txt
将 or ||
替换为 and &&
if (weight >= 1 && weight < 10) {// der code}
我的代码可以编译,当我 运行 它并输入一个数字时,它会输出 2 行代码而不是一行。我不确定我的 if 语句是否有问题导致它。但我想知道是什么导致我的程序输出 2 行而不是 1 行 if 语句?
#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;
}
这是输出
Enter the weight of your package: 9
Go see shiprates_small.txt
Go see shiprates_medium.txt
将 or ||
替换为 and &&
if (weight >= 1 && weight < 10) {// der code}