conversion from double to float in c++ - 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 ?

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);
}

C++ Returning Wrong Line of Code

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 :)

Wrong result while trying to divide

To learn C++, I follow an online class and I am trying to create a console mode game.
The game take a random word, split the word and ask the user to guess the word.
When the user don't wanna play anymore and quit the game, my program show some statistics (total of game played, game wins ...).
While I am trying to get the win percentage, I get wrong result.
Explanation (What I want) :
My user win 1 game and lose 1 game -> 1/2 * 100 = 50% (win percentage)
What is wrong (What I get) :
My function return 0 for 1/2 * 100.
void gameStatistics(int gameNumber, int gameWin, int defeats, int tries)
{
std::cout << "You quit." << std::endl;
float const winpercentage=float(gameWin / gameNumber) * 100; // C4244, resolved by casting the int into float.
std::cout << "Win average: " << winpercentage << std::endl;
std::cout << "Statistics: Number of games played: " << gameNumber << " Number of win: " << gameWin << " Number of defeat: " << defeats << " Number of tries: " << tries << std::endl;
}
I have been struggling for a while and I need someone to explain what I am doing wrong.
Thanks in advance
1/2 = 0 in integer logic.
1/2.0f = 0.5f in float logic.
This line float(gameWin / gameNumber) means that divide in integer space then convert the result to float space.
You should do this:
float(gameWin) / gameNumber
or even better:
static_cast<float>(gameWin)/ gameNumber
When you do float(gameWin / gameNumber) the division is still an integer division. You need to cast one of the operands as a float, like e.g. float(gameWin) / gameNumber.
Also note that unless you're on a small embedded platform, or writing code to run on a GPU, then there's really no reason to use float these days. Using double is just as "fast" as using float, and double is also the default floating point type (for example when using floating point literals).

(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

How do you represent a conversion factor by using a "const" symbolic constant?

I am a beginner at c++ who has a Python background and I am currently self teaching c++ before school starts so I can get ahead of the game. There's this practice problem that I found and I am about 95% complete, but the last 5% of the instructions in the question is a bit confusing to me. I am particularly stuck at the bolded part of last sentence.
Practice problem:
Write a short program that asks for your height in integer inches and then converts your height to feet and inches. Have the program use the underscore character to indicate where to type the response.Also use a const symbolic constant to repre-sent the conversion factor.
My CURRENT work:
// simpleheight.cpp
#include <iostream>
using namespace std;
int main ()
{
int number, inches, feet;
cout << "Enter your height in integer inches";
cin >> number;
inches = number%12;
feet = number/12;
cout << "You are " << feet << " feet" << " and" << inches << " inches" << endl;
cin.get();
cin.get();
return 0;
}
As you guys can see, it's nearly done, but I just don't get what the problem wants from me for the bolded sentence. Is it perhaps asking me to do something like this:
const int inches = number%12;
const int feet = number/12;
If not, can someone guide me through the last 5% of this question :D?
I would do like this.
static const unsigned int FACTOR = 12;
...
inches = number%FACTOR;
feet = number/FACTOR;
By doing a quick search you will notice that a symbolic constant is something that cannot be altered. So a const will be fine in this context.
you should use conversation value of inch to feet.
const double incToFeet = 0.08333;
and then use that value to convert