C++ Beginner, first program. finding velocity and distance - c++

Hey I'm a beginner taking an intro to C++ class, and this is my first assignment to use the formulas: d=v0*t + 1/2*g*t^2, and v= v0 + g*t. where v0 stays constant at 0 and g also stays constant at 9.807 m/s^2. I keep getting these errors and cannot seem to fix them, and im sure this code is incorrect, so can you help me figure this out?
#include <cstdlib>
#include <iostream>
#include <math.h>
using namespace std;
const float GRAVITY = 9.807, INITIALVELOCITY = 0;
int time;
void gettime()
{
cout << "Please enter the time in seconds." << endl;
cin >> time > endl;
} //end function Time
int main(int argc, char *argv[])
{
float distance, velocity, time;
void getTime(void);
cout.setf (ios::fixed,ios::floatfield);
cin >> time;
while (time > 0) {
distance = INITIALVELOCITY * time + (0.5 * GRAVITY * pow(time, 2));
velocity = INITIALVELOCITY + (GRAVITY * time);
cout.precision (0);
cout << endl << "WHEN THE TIME IS" << time << "SECONDS THE DISTANCE"
"TRAVELED IS" << distance << "METERS THE VELOCITY IS" << velocity <<
"METERS PER SECOND.";
cout. precision(1);
cout<< time << distance << velocity << endl << endl;
}
system ("PAUSE");
return EXIT_SUCCESS;
} //end main

The name time of the global variable is used as the name of one of standard library function, so you have to give another name to the variable.
remove junk > endl after cin >> time in gettime().
At least this will make the code compilable.
Then, inputting positive value will lead to infinite loop.
UPDATE: I think removing the global variable int time; and function gettime() is good because they are causing trouble and aren't used.

In addition to the problems mentioned by MikeCAT, you are not actually calling the gettime function. The line void gettime(void); is a function declaration, not a function call. Get rid of the void's: gettime();
After that, you may see you have a line cin >> time;. This accepts user input, but it has no prompt, so it would look like the program is doing nothing.
As far as getting the time, it's better if you have gettime() return an int: int gettime() and not have time declared as a global variable.

Related

using fmod in a function, loop logic is returning unexpected value

I am writing a program that takes the cost of an item, and the amount payed, and calculates how much of each coin you should get back in change (quarter, dime, nickel, penny). In the function that is calculating how many quarters are needed back, it always returns 2
float calculateCoins(float change)
{
int x=1;
float result=1;
while (result>0)
{
result =fmod(change, (.25 * x));
x++;
}
return x;
I am not sure what is wrong.
Also, excuse my inefficient code and probably ugly code, I am still learning
#include <iostream>
#include <math.h>
using namespace std;
float calculateChange(float, float);
float calculateCoins(float);
int main()
{
float amountPay, amountDue, changeDue, quarter;
cout << "This program calculates how much change should be returned "
<< "\nwhen a payment is made" << endl << endl;
cout << "Please input the cost of the item:" << endl;
cin >> amountDue;
cout << endl << "Please input the amount paid:" << endl;
cin >> amountPay;
changeDue = calculateChange(amountDue,amountPay);
quarter = calculateCoins(changeDue);
cout << changeDue << endl;
cout << quarter << " quarters needed";
return 0;
}
float calculateChange(float amount, float payment)
{
return payment-amount;
}
float calculateCoins(float change)
{
int x=1;
float result=1;
while (result>0)
{
result =fmod(change, (.25 * x));
x++;
}
return x;
}
Your problem is, that the logic behind function calculateCoins(float change) is wrong.
You first initialize result with a value of 1.
In your loop, you check against result > 0.
In your first iteration, this will always be true since you have initialized result with 1. In your loop body, you change the value of result to the modulo and increase your value of x which is now 2. The loop only stops, if the modulo of your change and x is 0. This is clearly not what you expect.
Try this:
cost = 1.1
paid = 2
and you end up with an infinite loop.
take this as a start point:
float calculateCoins(float change)
{
int x=1;
float result=1;
while (change - x*0.25 > 0)
{
x++;
}
return x;
}
I'm not sure what your expected result is.
Try to figure out what happens if you input strange numbers like cost = 1.1 paid = 2.
#D-Russ. First your function CalculateCoins is returning an int but you demand a float as output. If this is what you really want, consider casting the result before returning it. Second, you should use the appropriate remainder function from the math library.
Your code could change to the following:
int calculateCoins(float change)
{
int x=1;
float result=1;
while (result>0)
{
result =fmodf(change, (.25f * x)); // Note the use of "fmodf"
x++;
}
return x;
}
In fact, the number of quarter returned is an int, doesn't it make sense.
Note that in my suggested function, instead of float CalculateCoins(float change), I wrote int CalculateCoins(float change).

Why isn't the variables arithmetic working?

Here is code:
#include<iostream>
#include<string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
int score_one;
int score_two;
int score_third;
int final_score = score_one * score_two * score_third;
int main()
{
cout << "What was your first score?" << endl;
cin >> score_one;
cout << "What was your second score?" << endl;
cin >> score_two;
cout << "What was your third score?" << endl;
cin >> score_third;
cout << "Your average score is: " << final_score << endl;
return 0;
}
Originally I am trying to get the average, by dividing the three scores, but that doesn't work, nor my arithmetic. It does not even multiple the variables. I use cin to get the numbers. Not sure what I am missing.
At the time that you assign to final_score, the values of the other scores are 0 (as you haven't assigned to them yet and they're global). You then read into the scores, but never update final_score!
You need to add this after you read in the third score:
final_score = score_one * score_two * score_third;
This will update final_score.
I would also suggest staying away from global variables. I'd also suggest initializing your variables when you declare them to avoid garbage values.
Also, you're not actually calculating the average! To do that, you'll need to add your values and divide by 3, since you have 3 values total. But you've declared final_score as an integer, so you won't be able to store the average with full precision. I'd suggest declaring as a double.
Taking into account all these changes, your code will look like:
int main()
{
int score_one = 0;
int score_two = 0;
int score_third = 0;
double final_score = 0;
cout << "What was your first score?" << endl;
cin >> score_one;
cout << "What was your second score?" << endl;
cin >> score_two;
cout << "What was your third score?" << endl;
cin >> score_third;
final_score = (score_one + score_two + score_third) / static_cast<double>(3);
cout << "Your average score is: " << final_score << endl;
return 0;
}
This line should be moved after you cin to the variables on the right hand side of the equation
int final_score = score_one * score_two * score_third;
cout << "Your average score is: " << final_score << endl;
The variable isn't somehow recomputed when those variables are later set.
This part
int final_score = score_one * score_two * score_third;
should be inside main() after the last cin.
You have already received some answers, but I would like to offer another point of view.
It seems to me that you are used to a program like Excel, where you can set a cell to a formula (like the product of 3 other cells), and then, whenever you change any of those cells, the product is immediately updated, automatically. C++ (and, in general, programming languages) does not work like that. When you write a line like
int final_score = score_one * score_two * score_third;
you are not setting a rule, which will cause the value to be recalculated. The approach is different!
A program is executed from the beginning to the end (in practice, from the top to the bottom), and every time you assign a value to a variable (like final_score), what you are doing is reading the current value of the input variables (here, your three scores), calculating the result (which in this case is undefined, because you haven't initialised any of the scores), and assigning it to the variable, just this time. That's it. If you later change the scores, the change will not be reflected automatically on your final_score. If you want the value to be recalculated, you have to do it manually. That's why you have to move that line after the lines that read the input from the user, as the others have said.
You really should not use global variables, see here on why you should avoid them.
Next, instead of doing using std::cin etc. Just get used to typing it.
Lastly, use appropriate flags in your compiler to help you catch mistakes. The compiler is meant to be your friend. A good compiler would tell you,
int score_one;
int score_two;
int score_third;
int final_score = score_one + score_two + score+third / 3;
Is not initialized. To really achieve what you are thinking, you could use a function that will return a double. And that would look something like
double doAverage(int score1, int score2, int score3)
{
return (score1 + score2 + score3) / 3.0;
}
But that will probably come later in your coding practices.
#include<iostream>
int main()
{
// Delare your variables here and initialize them to zero.
int score_one = 0;
int score_two = 0;
int score_third = 0;
double final_score = 0;
std::cout << "What was your first score?" << std::endl;
std::cin >> score_one;
std::cout << "What was your second score?" << std::endl;
std::cin >> score_two;
std::cout << "What was your third score?" << std::endl;
std::cin >> score_third;
// Take all scores and divide it. This is the important part since
// order matters in your code.
final_score = (score_one + score_two + score_third) / 3.0;
std::cout << "Your average score is: " << final_score << std::endl;
return 0;
}
You're on the right track, you just have to look at your code and read it outloud to yourself. One of the best things you can do in programming is starting from the top and saying, "Okay, where does this break?" And follow it line by line making sense of it.

c++ Passing var from function to function then display result in main function

How do I pass the user entered distance gathered from one function to another function to calculate a shipping cost? And then show the cost via the int main function?
My distance function
double getDistance(double distance)
{
cout << "Enter the distance to be shipped: (min 10 Mi, max 3000 Mi): ";
cin >> distance;
while(distance<=10 || distance>= 3000){
cout << "We do not ship less than 10 miles or more than 3000 miles,
please reenter: ";
cin >> distance;
}
return distance;
}
I was thinking I could return distance and then use it in another function?? Is that right?
I need the variable distance to calculate the final shipping cost in another function ie calcCost then in the main function int main() simply display it cout << "the cost is " << finalCost << endl;
How do I pass the variable distance to another function to calculate cost and then display the cost via the int main() function?
Yes, you can use the returned value of distance in the main function as a parameter for another function:
int main(){
distance= getDistance();
finalCost = calculatefinalCost(distance);
..
}
By the way: you don't need a parameter in getDistance, the value will be replace by the user input anyway.

I keep getting 0's when I run my program even though the "user" inputs numbers || c++ painting job

c++ and I'm trying to figure out why my code returns 0's from a few statements after the user inputs some float numbers. I'm not sure why. Maybe someone can help:
This is what I get after running my method and answering the questions before it:
The number of gallons of paint required is: 0 gallons
Hours of labor that is required: 0 hours
.
Also ignore the () around my # in the beginning. I will put periods between lines to make it look neater on this website.
/**
* A painting company has determined that for every 160 square feet of wall
space, one gallon of paint and 3 hours of labor are required.
* The company charges the $28.00 per hour for labor.
* Design a modular program that allows the user to enter the number of rooms
that are to be painted,
* the approximate square feet of wall space in each room (may differ from room
to room), and the price per gallon of paint.
* It should then create a report that includes a fancy company header and
displays the following information:
* The number of gallons of paint required: (Rounded up to the next full
gallon)
* The hours of labor required:
* The cost of the paint:
* The labor charges:
* Total cost of the paint job:
* Requirements:
* Input validation: The program should not accept a value less than 1 or
more than 12 for the number of rooms
* Should not accept a value less than 100 for the square
footage of a room.
* Should not accept a value less than $10.00 or more
than $25.00 for the price of a gallon of paint
*
* Lets do this...
*/
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
float priceOfGallon(float);
float numberOfGallons(float, float);
float totalWallArea(float, float, float);
float laborHours(float, float);
void fancyCompanyHeader();
int main() {
float area;
float totalArea;
float min_labor = 3;
float number_of_rooms;
float number_of_gallons;
float price_of_gallon;
totalWallArea(area, totalArea, number_of_rooms);
priceOfGallon(price_of_gallon);
numberOfGallons(number_of_gallons, totalArea);
laborHours(number_of_gallons, min_labor);
fancyCompanyHeader();
return 0;
}
// function that gets the number of gallons needed for the total area
float numberOfGallons(float number_of_gallons, float totalArea) {
number_of_gallons = (totalArea / 160.0);
std::cout << "The number of gallons of paint required is: " <<
number_of_gallons << " gallons" << std::endl;
}
float priceOfGallon(float price_of_gallon){
std::cout << "Please enter the price per gallon: " << std::endl;
cin >> price_of_gallon;
while(price_of_gallon < 10.00 || price_of_gallon > 25.00) {
std::cout << "The price should be between $10.00 and $25.00. Please try again: " << std::endl;
cin >> price_of_gallon;
}
}
float totalWallArea(float area, float totalArea, float number_of_rooms) {
std::cout << "Please enter the number of rooms that needs to be painted:" <<
std::endl;
std::cin >> number_of_rooms;
while(number_of_rooms < 1)
{
cout << "Number of rooms must be at least one. Please try again: " <<
std::endl;
cin >> number_of_rooms;
}
for(float i = 1; i <= number_of_rooms; i++)
{
cout << "Please enter the square feet of wall space needed for Room " <<
i << std::endl;
cin >> area;
while(area < 100)
{
std::cout << "The area should be 100 or greater. Please try again: "
<< std::endl;
cin >> area;
}
totalArea += area;
}
}
// I will finish this method later
float laborHours(float number_of_gallons, float min_labor) {
min_labor = number_of_gallons * 28.00;
std::cout << "Hours of labor that is required: " << min_labor << " hours "
<< std::endl;
return min_labor;
}
You need to make all of those variables you are modifying global (Declared outside of int main()). In C++, when you give a function a variable, it will just copy the contents of the variable into the function's variables: the original variable passed in remains constant. Thus, your uninitialized floats default to 0 and are not changed by any of the functions, so when they are given to the laborHours function or numberOfHours function, 0s are passed into each.
Example with much better practices than in your code (it's ok, everyone starts by writing atrocious code) :
#include <iostream>
int walls,rooms,total_walls; //It only makes sense if all of these are integers.
//These are global declarations, they can be modified by any function in the program
void input_walls() {
/* Functions are notated as so in C++:
{return type} {function_name}({input},{input},...)
It's pointless to annotate functions that don't return anything
with a declaration of a float return type (they'll just return 0 */
std::cin >> walls;
while(walls < 0) {
std::cout << "Please input a positive amount of walls per room.";
std::cin >> walls;
}
}
void input_rooms() {
std::cin >> rooms;
while(rooms < 0) {
std::cout << "Please input a positive amount of rooms";
std::cin >> rooms;
}
}
void calculate_result() {
total_walls = walls*rooms;
}
void output_result() {
std::cout << "I'll need to paint " << total_walls << " walls!" << std::endl;
}
int main() {
input_walls();
input_rooms();
calculate_result();
output_result();
}
This still isn't the best way to write this, but it's still the exact same thing you were trying to do. Now try rewriting what you were trying to do in this style!
TLDR/Quick fix: Make the variable definitions global, cut out the arguments from the functions.

Really need some assistance, first programming project

My formatting is really bad, and I'm sorry for that, but I'm still in the very early stages of learning C++. Anyway, no matter what I try, I always get an expected unqualified ID error on line 51. Any assistance would be greatly appreciated! And no, the code is not finished, its due March 20th, just wanted to start on it early. And this is NOT how I wanted to format it, but this is how it was stated on the rubric. I'm brand new to functions, so yeah, any help would be awesome!
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int menu (int); //Menu prototype for 4 options
int main()
{
const int numWidth = 4;
int choice, pick;
cout << "Welcome! Please select your choice by entering 1, 2, 3, or 4!" << endl;
cout << "1:";
cout << right << setw(numWidth) << " Enter the Grades" << endl;
cout << "2:";
cout << right << setw(numWidth) << " Display the Grades" << endl;
cout << "3:";
cout << right << setw(numWidth) << " Show overall Grade" << endl;
cout << "4:";
cout << right << setw(numWidth) << " Exit the program" << endl;
cout << "Select your choice and press enter ";
cin >> choice;
pick = menu(choice);
cout << pick;
if (choice ==1)
{
cout << ". Please enter your grades.\n";
}
float AssignmentGrade(float, float, float, float); // Assignment Grade Prototype
{
float asgnment1, asgnment2, asgnment3, asgnment4, total;
cout << "First, enter your 4 assignment grades ";
cin >> asgnment1 >> asgnment2 >> asgnment3 >> asgnment4;
total = AssignmentGrade (asgnment1, asgnment2, asgnment3, asgnment4);
cout << total;
return 0;
}
}
float AssignmentGrade (float num1, float num2, float num3, float num4)
{
float asgnmentgrade;
asgnmentgrade = num1*0.05 + num2*0.05 + num3*0.05 + num4*0.05;
cout << "Total points, including weights, for assignment grade is ";
return asgnmentgrade;
}
float LabTestGrade (float, float, float); // Right here, line 51, is where I get expected unqualified ID error before {
{
float lab1, lab2, lab3, total;
cout <<"Next, please enter your 3 lab test scores!";
cin >> lab1 >> lab2 >> lab3;
total = LabTestGrade (lab1, lab2, lab3);
cout << total;
return 0;
}
float LabTestGrade (float lab1, float lab2, float lab3)
{
float LabGrade;
LabGrade = lab1*0.10 + lab2*0.10 + lab3*0.10;
cout << "Total points earned from lab tests is";
return LabGrade;
}
int menu (int num)
{
int option;
option = num;
cout <<"You have selected ";
return option;
}
Delete unnecessary ; in your 51st line: float LabTestGrade (float, float, float);
Dont forget that ; is used for the end of a command. If you define a function, you don't use it. Look at th following model:
float function (float parameter) {
command();
command();
return 0;
}
Edit: There's the same syntax error in your 31th line.
Delete ; again in float AssignmentGrade(float, float, float, float);
You will find yourself running into a few other problems with this function, apart from the original unqualified ID that #Nichar answered.
At Line 50 you have:
float LabTestGrade (float, float, float) { // Function Code }
and at Line 60 you have:
float LabTestGrade (float lab1, float lab2, float lab3) { // Function Code }
This will cause a compile error as you are trying to define another function with the exact same name and parameters. (Redefinition error)
Although these functions may look slightly different as you have named the parameters of the second one (float lab1, float lab2, float lab3), to the compiler it will simply see two functions that are named the same and take in the same types as parameters.
That being said, you can delete the parameters in the first LabTestGrade() as they aren't actually being used inside its function.
float LabTestGrade() { // Function Code }
Finally, you are also going to want to swap around the order that these two functions are being defined. I suggest googling C++ Scope but basically the first LabTestGrade() is making a call to the second LabTestGrade(float lab1, lab2, lab3) like so.
total = LabTestGrade(lab1,lab2,lab3);
However, the second LabTestGrade hasn't been defined yet within your program so it will try to call the first LabTestGrade() again and give you an error because the first LabTestGrade() doesn't take in any parameters now and this line of code is trying to pass into it three floats into a function that takes in nothing.
Alternatively, you could just declare the functions above your main function like you had done for your menu function.
float LabTestGrade();
float LabTestGrade(float lab1, float lab2, float lab3);
int menu(int) // Menu prototype for 4 options
Hi even im a beginner but heres what i think -
First of all
The menu prototype in the beginning is incorrect . Prototypes should be exactly same as the function itself .
Correct prototype will be
int menu (int num);
In line 51 , in the parameter bracket, try writing the full name of the float types you r trying to get. Also remove the semicolon. Ex:-
float LabTestGrade (float a , float b , float c) { }
A similar mistake is made in the AssignmentGrade function which takes 4 floats.
Try writing the full name as parameters. Remove the semi colon.
Write the function prototypes separately in the beginning outside the main.
You have to create a separate prototype for every function you make and remember - prototypes should have the same name as the function. Just you need to replace the curly braces with a semi colon.
Hope this helps.
EDIT:- You can also try writing the functions outside main and then use prototypes in the beginning outside the main.