I've been facing the problem in which an error message: In function 'int main()': 16:1: error: 'else' without a previous 'if'. I've included an "if" on line 11 but the error message continues to show up. Could anyone please give me some advise on how to alter the coding?
#include<iostream>
#include<sstream>
using namespace std;
int main()
{
float r, result, h;
cout<<"volume of cylinder, please insert radius:\n";
cin>>r;
result=3.1415926535*r*r;
if(r<0);
{
do (r<0); while (r<0); {cout<<"Number entered is negative. Please insert another non-negative integer: \n";
cin>>r;
}
else;
{
cout<<"Area of circle is "<<result<<". Please insert Height: \n";
cin>>h;
if (h<0) {cout<<"Number entered is negative. Please insert another non-negative integer: \n";
cin>>h;
result=result*h;
cout<<"The volume of the cylinder is "<<result<<".";}
else (h>0);
{
result=result*h;
cout<<"The volume of the cylinder is "<<result<<".";}
}}}
You're getting the error because
You have a lot of semicolons on the wrong places. And using loops wrong.
1 2 3 4 5
if (r<0)
{
do (r<0) while (r<0); {cout << "Number entered is negative. Please insert another non-negative integer: \n";
cin >> r;
}
Change it to
1 2 3 4
while (r < 0) {
cout << "Number entered is negative. Please insert another non-negative integer: \n";
cin >> r;
}
Then just do this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
if (r >= 0)
{
cout << "Area of circle is " << result << ". Please insert Height: \n";
cin >> h;
if (h<0)
{
cout << "Number entered is negative. Please insert another non-negative integer: \n";
cin >> h;
result = result*h;
cout << "The volume of the cylinder is " << result << ".";
}
else (h>0);
{
result = result*h;
cout << "The volume of the cylinder is " << result << ".";
}
}
It looks like you dont quite know how loops and if statements work. I suggest watching the tutorials on them here -
You have semicolons (;) after the if on line 11, the else on line 16. Get rid of those semicolons.
Also on line 25, I see an else with a boolean condition. If statements must take this form: