C++ Returning Wrong Line of Code - c++

I was instructed to design an algorithm that would allow the user to calculate the perimeter and area of a rectangle, but that's too easy:
Perimeter = 2 (Length + Width)
Area = (Length * Width)
I wanted to build a program using a similar construction to one my professor showed us on the first day so that I could have a program collect data from the user, calculate the perimeter and area of the rectangle for me, and then output the answer back to the user. That was easy enough, so I decided I wanted the program to also tell me whether or not the length and width that the user entered was the length and width of a rectangle or a square.
With the code I wrote, the program always returns that the length and width entered are the length and width of a square. I am not sure where I went wrong:
Here is my code:
#include<iostream>
using namespace std;
int main() {
//Declaration
int length;
int width;
int perimeter;
int area;
//Collect Data
cout << "Let's calculate the perimeter and area of a rectangle\n";
cout << "What is the length of the rectangle?: ";
cin >> (length);
cout << "What is the width of the rectangle?: ";
cin >> (width);
//Calculation
(perimeter) = 2 * (length + width);
(area) = (length) * (width);
//Output Data
cout << "The perimeter of the rectangle is: " << (perimeter) << "\n";
cout << "The area of the rectangle is: " << (area) << "\n";
//For some reason, the code is not able to recognize what I have designed.
//No matter what input for length and width, when the program executes it returns that I entered the length and width of a square.
if ((length) = (width))
cout << "Hey! You entered the length and width of a Square!\n";
else
cout << "You entered the length and width of a Rectangle!\n";
system("pause");
return 0;
}
Any help would be greatly appreciated! Thank you so much!

You want a double equals:
if (length == width)
A single equals (=) performs assignment, double equals (==) performs a comparison.

In your if-statement you are assigning width to length, not comparing.
It should be: if (length == width)
The reason why your if-statement evaluates to true is because it checks whether the result of the evaluation (which is the value of length) is different from zero.
That's because a bool is internally represented as an int, where false is defined as 0 and true else.
And since width is usually not 0 it would always result in true.
You can test it out by entering 0 for width.

One thing I would recommend is looking into using a debugger to step through each line of your code as it runs one at a time. If you are using VS you have one built right in!
I think if you used a debugger you would have noticed that when the if was running it was doing the assignment rather than the comparison. Just a thought for the future.
I'm sure everyone can say they have caught many silly bugs with a debugger. Good job :)

Related

How do I use function to call for a fail or pass on multiple tests?

I am trying to figure out how to call for a function. I have to be able to enter a load amount and see if it passes three tests. These are the equations given.
Buckling Load:
Max Load = (0.3*E*area) / ((length/width) * (length/width))
Compressive stress:
Max Load = area * maximum compressive strength
Slenderness limits:
Length/width <= 50
E is the modulus of elasticity (1,700,000 psi), the area is the cross-sectional area in square inches and the maximum compressive strength = 445 psi (Douglas fir). Assume the columns to be used are square and are available in intervals of 2 inches (2x2, 4x4, 6x6, etc.). I have to use a different function for each one! HELP :/
I currently have :
{
int strength, area, length, width, e, maxLoad, bucklingLoad, compressiveLoad, slenderness;
float bucklingLoad;
e = 1700000,
maxLoad =
cout << "Jessica's Engineering Company Analysis" ;
cout << "\n*************************************";
cout <<"\n\nPlease enter the expected load on the column in pounds: ";
cin << maxLoad;
cout << "\nPlease enter the length of the column in inches: ";
cin << length;
cout << "\n\n_Beam with wide of 2 inches - " ;
cout << "\n_Beam with wide of 4 inches - " ;
cout << "\n_Beam with wide of 6 inches - " ;
cout << "\n_Beam with wide of 8 inches - " ;
}
I'm not going to do the whole thing, and you should absolutely learn C++ properly from a book or other resource, because asking open-ended questions is going to be a really slow, frustrating and inefficient way to figure it out - but I can give you a hint to get started.
Buckling Load:
Max Load = (0.3*E*area) / ((length/width) * (length/width))
So we can translate this directly into a function, like
double calcBucklingLoad(int length, int width, int area)
{
return (0.3*E*area) / ((length/width) * (length/width));
}
(so long as we first define E somewhere, like
const double E = 1700000;
or something similar. It could be another function parameter if you want to reuse the code for different materials).
Then testing whether the max load is greater than the buckling load is just
bool isBucklingLoadOK(int maxload, int length, int width, int area)
{
return maxload < calcBucklingLoad(length, width, area);
}

Having garbage numbers while calculating percentage

So, I hate to ask, but, I'm having some issue with this, I'm new to C++ and I'm just starting out. Everything is done for the most part. Expect for a little thing.
Line 35-36 should be calculating the average (Which for some reason, I haven't been able to get it to work.)
Line 41-47 should print out the percentage that heads/tails was landed on with precision to one decimal, and then print out the correct numbers of * to represent the percentage.
But, when I run it, my heads/tail count is messed up. As well as my percentage numbers. I'm just looking for a push in the right direction.
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <iomanip>
using std::cout; using std::cin; using std::endl;
using std::fixed; using std::setprecision;
int main()
{
srand(time(0));
int userInput,
toss,
headsCount,
tailsCount;
double headsPercent = 0,
tailsPercent = 0;
cout << "How many times do you want to toss the coin? ";
cin >> userInput;
while(userInput < 0)
{
cout << "Please enter a positive number: ";
cin >> userInput;
}
for(int i = 1; i < userInput; i++)
{
toss = rand() % 2;
if(toss == 0)
headsCount++;
else
tailsCount++;
}
headsPercent = userInput / headsCount * 100;
tailsPercent = userInput / tailsCount;
cout << "Heads: " << headsCount << endl
<< "Tails: " << tailsCount << endl << endl;
cout << "Heads Percentage: " << fixed << setprecision(1) << headsPercent << " ";
for(int b = 0; b < headsPercent; b++)
cout << "*";
cout << "\nTails Percentage: " << tailsPercent << " ";
for(int b = 0; b < tailsPercent; b++)
cout << "*";
return 0;
}
In addition to the uninitialized variables here, that others have pointed out, the calculations are all wrong.
Take out paper and pencil, and run some your own calculations the old-fashioned way.
Let's say there were five tosses, three heads, two tails. This means that (after fixing the uninitialized variables):
userInput=5
headsCount=3
tailsCount=2
Now, here's how you're calculating your supposed percentages:
headsPercent = userInput / headsCount * 100;
tailsPercent = userInput / tailsCount;
So, using your own numbers, you will get:
headsPercent = 5 / 3 * 100
tailsPercent = 5 / 2;
Does this look right to you? Of course not. You can do the arithmetic yourself. Divide 5 by 3 and multiply by 100. This is integer division, so five divided by three is 1, multiplied by 100 is 100. Five divided by two is two. So you get 100% and 2% here.
Of course, that's wrong. Two and three times, out of five, is 40% and 60%, respectively.
Writing a program means:
A) Figure out how calculations need to be made
B) Write the code to do the calculations.
You're still on step A. You need to figure out how you want to make these calculations so they're correct, first.
This has nothing really to do with C++. If you were using any other language, and coded this, in that manner, you'll get the same wrong answers.
The only thing this might have to do with C++ is that integer division, in C++ does not produce a fractional amount. It's integer division. But that's not your only problem.
Firstly u have to correct ur basics of mathematics.
Calculating %age means
example
(Marks obtained)/(Total marks)*100
Not (Total marks/marks obt)*100
Dividing any no by 0 is not defined. So if ur current code randomly assign toss or head =0, then obviously u will have errors.
Secondly talking about codes, U should either initialize i from 0 , or u should use
for (i=1; i<=userInput; i++)
As otherwise the head+toss value will be userInput-1.
Also remember to initialise variables like
Int headsCount=0;
etc. As the variable will take any random value if not initialised to a fixed no. (Though it does not creates a problem here)
And just change the datatype
int userInput,
toss,
headsCount,
tailsCount;
To
double userInput,
toss,
headsCount,
tailsCount;
This will solve your problem.
Advice: Please use
using namespace std;
in the starting of ur programs as u have to type a lot of std::
Welcome to C++. You need to initialise your variables. Your compiler should have warned you that you were using a variable without initialising it. When you don't initialise a value, your program has undefined behaviour.
I'm talking about headsCount and tailsCount. Something like this should be fine:
int headsCount = 0, tailsCount = 0;
Also note that your loop should start at 0, not 1, since you are using the < operator on the final condition.
Finally, your percentage calculations are backwards. It should be:
headsPercent = headsCount * 100 / userInput;
tailsPercent = tailsCount * 100 / userInput;
Now, there's a weird thing that might happen because you are using integer division. That is, your percentages might not add up to 100. What's happening here is integer truncation. Note that I dealt with some of this implicitly using the 100x scale first.
Or, since the percentages themselves are double, you can force the calculation to be double by casting one of the operands, thus avoiding integer truncation:
headsPercent = static_cast<double>(headsCount) / userInput * 100;
In fact, since the only two possibilities are heads and tails, you only need to count one of them. Then you can do:
tailsPercent = 100 - headsPercent;
1) This loop should start from 0:
for(int i = 1; i < userInput; i++)
2) The divisions are not correct:
//headsPercent = userInput / headsCount * 100;
//tailsPercent = userInput / tailsCount;
headsPercent = headsCount / userInput * 100;
tailsPercent = tailsCount / userInput * 100;
3) Finally:
cout << "\nTails Percentage: " << fixed << setprecision(1) << tailsPercent << " ";

(C++)1 dimensional battleship game help? advice for improvement

Unfortunately I do not have the Instructor to aid me with this assignment over the weekend and I am stuck. I'm just learning C++ and I've taken a Logic and Design class for Programming but like I said I'm very new to C++. I'm having a hard time catching up to the rest of the students.
I'd like if someone could list improvements and maybe clarify if I've done anything wrong in comparison to the assignment statement. I do really appreciate the help!
My code is repetitive and I'm sure I could go another way into displaying the array values without all that code. An error also pops up after use of the application that says:
"Run-Time Check Failure #2 - Stack around the variable 'enemy' was corrupted.
If there is a handler for this exception, the program may be safely continued."
The assignment is:
"Create a Battleship struct containing 5 one-dimensional integer coordinates representing its location within a region (of any size). Instantiate 2 copies of the struct and have the user enter a single coordinate for each Battleship. Design your code to take this single coordinate and use it to populate the remaining 4 coordinates for each ship. Do this for both ship structs. Then, have your code calculate the numeric distance between the 2 ships based on their respective coordinates. Finally, display the resulting distance to the user with an English language sentence."
My code as for right now is :
#include <iostream>
#include <string>
using namespace std;
struct Ship
{
int x[5];
int y[5];
};
int main()
{
Ship good;
Ship enemy;
good.x[0] = 0;
enemy.y[0] = 0;
cout << "Enter a coordinate (out of 100) for good ship: "<< endl;
cin >> good.x[0];
good.x[1] = good.x[0] + 1;
good.x[2] = good.x[1] + 1;
good.x[3] = good.x[2] + 1;
good.x[4] = good.x[3] + 1;
cout << "Good ship coordinates:" << endl;
cout << good.x[0]<< "*" << endl;
cout << good.x[1]<< endl;
cout << good.x[2]<< endl;
cout << good.x[3]<< endl;
cout << good.x[4]<< endl;
cout << "Enter a coordinate (out of 100) for enemy ship: "<< endl;
cin >> enemy.y[0];
enemy.y[1] = enemy.y[0] + 1;
enemy.y[2] = enemy.y[1] + 1;
enemy.y[3] = enemy.y[2] + 1;
enemy.y[4] = enemy.y[3] + 1;
cout << "enemy ship coordinates:" << endl;
cout << enemy.y[0]<< "*" << endl;
cout << enemy.y[1]<< endl;
cout << enemy.y[2]<< endl;
cout << enemy.y[3]<< endl;
cout << enemy.y[4]<< endl;
int distance=0;
distance = good.x[1] - enemy.y[1];
cout << "The distance between good ship and enemy ship is: " << distance << endl;
system("pause");
return 0;
}
The error probably comes from having only 4 coordinates in each struct, not 5. When you declare an array with int x[4];, it will only have 4 elements, namely x[0] to x[3].
There are a number of other problems:
You do not need two structs for two ships. Use just one. That's the whole point of structs/classes: to represents classes of objects. Use only one struct (named e.g. Ship) and declare both your ships good and enemy to have that type.
Don't be afraid of both the enemy ship and the good ship having x coordinates. The compiler and the computer won't get confused at that, and neither should you.
Learn to use loops. Even if you get confused at first, remember that loops are one of the most (if not the most) important tools at a programmers disposal. Think what would happen if you had 100 ships, each with 100 coordinates...
Remember, again, that the first element of an array is at index 0, not index 1. (And the last element is at index N-1.)
Calculating the distance is a little more complex than you've written. Can the distance between two objects ever be negative? What happens if the enemy ship's coordinate is greater than the friendly ship? What's the actual formula for one-dimensional distances?
Remove unused code. What's the use of that region variable? Have you used it anywhere?
UPDATE: (For anyone reading in the future, remember that OP has updated and modified their question and code, to the point that some of my point would not apply or would apply differently.)
Do you REALLY need both xs and ys in Ship?
Not sure if the use of system("PAUSE") is something your instructor taught, but that's definitely something you could improve on, too. Explained here
So starting with
Create a Battleship struct containing 5 one-dimensional integer coordinates representing its location within a region (of any size). Instantiate 2 copies of the struct and have the user enter a single coordinate for each Battleship
You need a single struct:
struct Ship
{
int x[5];
};
Now make 2 copies
int main()
{
Ship good;
Ship bad;
...
Then the rest looks good, it compiles and runs without any issues on my computer. You can add a function to populate the ship to reduce the number of code
Ship createShip(int startPos) {
Ship newShip;
newShip[0] = startPos;
// ... <- rest of your code that you have to populate
return newShip;
}
int main()
{
int pos;
cout << "Enter a coordinate (out of 100) for good ship: "<< endl;
cin >> pos;
Ship good = createShip(pos);
//...
//... <- Get pos of bad ship
Ship bad = createShip(pos);
}
Then you can also create a simular function that prints the location of the ship

conversion from double to float in c++

I am new to programming. Here is part of my assignment, which requires using pass-by-reference. After I compile it and type in the values for win, draw and loss respectively,it returns me nothing. I don't know whether it is due to the problem in calling the function or the floating point.
void Cfunction(int win, int draw, int loss, float& point)
{
point = win * 2.5f + draw * 1 + loss * 0;
}
int main(void)
{
int win, draw, loss;
float point;
cout << "Please input the game record in the following order: win draw loss " << endl;
cin >> win >> draw >> loss;
Cfunction(win, draw, loss, point);
cout << "The total score for the team is " << point << endl;
}
Look good to me.
You could verify that your cin >> ... has finished by adding a cout << "calculatin total score...." << std::endl;.
(Note: std::cin >> wins has the wins variable passed by reference, too :))
Indeed, as #David Hefferman suggested, learn to use the debugger. Will save you a huge amount of time in the (very near) future.
Looks fine to me too. You do know that you have to add the numbers one by one on their own lines, e.g. 5 , 3 , 4 ?

Mathematics errors in basic C++ program

I am working with a basic C++ program to determine the area and perimeter of a rectangle. My program works fine for whole numbers but falls apart when I use any number with a decimal. I get the impression that I am leaving something out, but since I'm a complete beginner, I have no idea what.
Below is the source:
#include <iostream>
using namespace std;
int main()
{
// Declared variables
int length; // declares variable for length
int width; // declares variable for width
int area; // declares variable for area
int perimeter; // declares variable for perimeter
// Statements
cout << "Enter the length and the width of the rectangle: "; // states what information to enter
cin >> length >> width; // user input of length and width
cout << endl; // closes the input
area = length * width; // calculates area of rectangle
perimeter = 2 * (length + width); //calculates perimeter of rectangle
cout << "The area of the rectangle = " << area << " square units." <<endl; // displays the calculation of the area
cout << "The perimeter of the rectangle = " << perimeter << " units." << endl; // displays the calculation of the perimeter
system ("pause"); // REMOVE BEFORE RELEASE - testing purposes only
return 0;
}
Change all your int type variables to double or float. I would personally use double because they have more precision than float types.
int datatype stands for integer (i.e. positive and negative whole numbers, including 0)
If you want to represent decimal numbers, you will need to use float.
Use the float or double type, like the others already said.
But it ain't as simple as that. You need to understand what floating-point numbers actually are, and why (0.1 + 0.1 + 0.1) != (0.3). This is a complicated subject, so I won't even try to explain it here - just remember that a float is not a decimal, even if the computer is showing it to you in the form of a decimal.
use floats not ints an integer (int) is a whole number, floats allow decimal places (as do doubles)
float length; // declares variable for length
float width; // declares variable for width
float area; // declares variable for area
float perimeter; // declares variable for perimete
You've defined your variables as integers. Use double instead.
Also, you can look up some formatting for cout to define the number of decimal places you want to show, etc.