Else if statements not working properly

Hey. So I am pretty new to C++ programming only been doing it for a few weeks now. I have a midterm soon and my instructor posted a practice problem I have been trying to solve for a while now, but can't quite get it to do what I want it to. I am sure it is a simple error, but I need some help.
I was supposed to write a program that found that sum of rainfall over the course of three months to find out how much water tomato plants needed. It looked like this:
0 <= r < 2 1 Gallon
2 <= r < 7.5 0.5 Gallons
7.5 <= r Nothing needed!

So I wrote out my program and everything works fine, except my else if statements aren't really doing anything. No matter the sum that I put in, it always says "You need 1 gallon of water for your tomato plants!"

Here is the program so far:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <string>
using std::cout; using std::cin; using std::endl;
using std::string;

struct month
{
	string name;
	float rainfall;
};

float average(const month& m1, const month& m2, const month& m3)
{
	return (m1.rainfall + m2.rainfall + m3.rainfall) / 3;
}

int main()
{
	month m1{}, m2{}, m3{};

	cout << "Average Rainfall for 3 Months Calculator" << endl;
	cout << "Enter the first month: ";
	cin >> m1.name;
	cout << "Enter rainfall for " << m1.name << ": ";
	cin >> m1.rainfall;
	cout << "Enter the second month: ";
	cin >> m2.name;
	cout << "Enter rainfall for " << m2.name << ": ";
	cin >> m2.rainfall;
	cout << "Enter the third month: ";
	cin >> m3.name;
	cout << "Enter rainfall for " << m3.name << ": ";
	cin >> m3.rainfall;
	cout << "The sum of the rainfall is " << endl;
	cout << (m1.rainfall + m2.rainfall + m3.rainfall);
	cout << endl;

	if (0 <= m1.rainfall + m2.rainfall + m3.rainfall < 2) {
		cout << "You need 1 gallon of water for your tomatoes! ";
		cout << endl;
	}
	else if (2 <= m1.rainfall + m2.rainfall + m3.rainfall < 7.5) {
		cout << "You need 0.5 gallons of water for your tomatoes! ";
		cout << endl;
	}
	else if (7.5 <= m1.rainfall + m2.rainfall + m3.rainfall)
		cout << "You don't need to water your tomatoes! ";
		cout << endl;

	return 0;
}
closed account (48T7M4Gy)
0 <= r < 2 becomes

if (m1.rainfall + m2.rainfall + m3.rainfall >=0 && m1.rainfall + m2.rainfall + m3.rainfall < 2 )
Last edited on
closed account (E0p9LyTq)
Your if statements are not written correctly. For example:

if (0 <= m1.rainfall + m2.rainfall + m3.rainfall < 2)
should be
if (0 <= (m1.rainfall + m2.rainfall + m3.rainfall) && (m1.rainfall + m2.rainfall + m3.rainfall) < 2)
Hey it works now! Thanks so much guys I appreciate it. (:
Topic archived. No new replies allowed.