Keep getting an error for "answer" variable value must be a modifiable lvalue how do I fix this?
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int choice;
float
answer,
length,
width,
depth;
cout << "Please choose your option Square Feet enter: 1 Square Yards enter: 2 Cubic Yards enter: 3" ;
cin >> choice;
if (choice == 1)
{
setprecision(2);
cout << "You chosen the unit Square Feet";
cout << "Please enter the amount of square feet in length first then a space followed by width ";
cin >> length >> width;
(length * width = answer);
cout << "Your answer in square feet is " << answer;
}
if (choice == 2)
{
setprecision(2);
cout << "You chosen the unit Square Yards";
cout << "Please enter the amount of square yards in length first then a space followed by width ";
cin >> length >> width;
((length / 3) * (width / 3) = answer);
cout << "Your answer in square yards is " << answer;
}
if (choice == 3)
{
setprecision(2);
cout << "You chosen the unit Cubic Yards";
cout << "Please enter the amount of cubic yards with a space between all three units length, width, depth ";
cin >> length >> width >> depth;
((length * width * (depth / 12)) / 27 = answer);
cout << "Your answer in square feet is " << answer;
}
}
Hint: You can edit your post, highlight your code and press the <> formatting button. This will not automatically indent your code. That part is up to you.
You can use the preview button at the bottom to see how it looks.
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
int choice{};
double
answer{},
length{},
width{},
depth{};
std::cout << std::fixed << std::setprecision(2); // <--- Only needs done once.
cout <<
"Please choose your option\n""Square Feet enter: 1\n""Square Yards enter: 2\n""Cubic Yards enter: 3\n""Exit enter: 4\n"" Enter Choice: ";
cin >> choice;
if (choice == 1)
{
//setprecision(2); // <--- Does not work this way.
cout << "\nYou chosen the unit Square Feet\n";
cout << "Please enter the amount of square feet in length first then a space followed by width ";
cin >> length >> width;
//(length * width = answer);
answer = length * width;
cout << "\nYour answer in square feet is " << answer;
}
Many parts of C++ are evaluated from right to left. That is why line 34 does not work and line 35 does. The same would be true for the others.
Line 15 needs done this way because it works on the "cout" or file stream, so you need to tell it what you are using "setprecision" on.. The "fixed" tells it to use numbers and not scientific notation.
It is a good idea to initialize your variables when defined. The empty {}s will set the variables to (0) zero.
I changed the menu so the it is easier to read on the screen. Presentation can work in your favor.
Try to use the "\n" more than "endl" as the "endl" has more overhead and used often enough could slow the program down. Most times using "endl" is not noticeable.
Andy
P.S. "double" is the preferred type for floating point numbers.