How to solve c++ unwanted mathematical error - c++

I'm new to c++ so what I like to do is make numerous calculators of anything, varying from area calculators to quadradic formula and etc. Anyways I'm creating a triangle area calculator but there is one small problem but first here's my code:
#include <iostream>
#include <cmath>
using namespace std;
int triangle()
{
int base;
int height;
int area;
cout << "Enter base: ";
cin >> base;
cout << "Enter height: ";
cin >> height;
area = base * height /2;
cout << area;
return area;
}
int main ()
{
cout << "Formula Calculator \n";
cout << triangle();
return 0;
}
The input is this:
Enter base: (I enter 4)
Enter height: (I enter 5)
1010
As you can see the 5 * 4 * 1/2 is not 10 for some reason every number that the area is, is always digit doubled if you know what I mean for ex if the area is 20 the program will show 2020, please help.

You output the area twice.
cout << area; // here's once
cout << triangle(); // here's twice
I would suggest rethinking your code. Should the triangle function just compute the area or should it ask for input and do output? If the latter, why cout << triangle();?

When you are inside your function triangle(), check it's 2nd last line, It is cout<<area, let's say you have given input 4 and 5 so inside the body of the function, at cout<<area it will output the area. Now it returns area which is then outputted by 2nd last line of your program i.e cout<< traingle()//return value is outputted so that's why we are seeing 2 outputs. It is not only in the case of 4 and 5, but it will also output area 2 times in every case.

Related

C++: Is there a way to distinguish a user input if its on centimeter or not?

Heres the given:
Write a program to compute for the surface area and volume of a sphere if the unit of the radius
is in centimeters (cm).
Filename: exer10.cpp
Formulas: area = 4*pi*radius2
Volume = (4/3)*pi*radius3
I was skeptical because of the "if" on the given as you read it, now I don't know if what I did is right. But I have some ideas on how to do it
I Have a 2 ideas in mind 1st is where if I input a value there will be a formula to distinguish if that value is in centimeter, the thing is I don't know how.
2nd idea is I will use the if else method where after I input a value, it will ask if its in centimeter or not, if I type "Y" it will do its thing and continue its computation but if I type "N" it`ll will not compute and end the program.
Any suggestion guys?
By the way here's my code (My given ideas are not written here)
#include <iostream>
using namespace std;
int main()
{
float radius, area, volume;
cout << "This program computes for the surface area and volume of a sphere (centimeters)"
"\n\n";
cout << "Input the radius of a sphere    : ";
cin >> radius;
area = (4 * 3.1416 * radius * radius);
volume = (4 / 3) * (3.1416 * radius * radius * radius);
cout << "The surface area of a sphere is : " << area << "\n";
cout << "The volume of a sphere is       : " << volume;
return 0;
}
You can ask the user to input the unit. Consider this example, if it's in centimeters then perform the operation/task or else exit the program.
#include <iostream>
#include <string>
#include <cstdio>
int main() {
int radius;
std::string unit;
std::cout << "Enter radius of sphere in centimeters (e.g. 5 cm) : ";
std::cin >> radius >> unit;
if (unit != "cm") {
std::cout << "\nPlease enter in centimeters (e.g. 5 cm)";
exit(1);
}
// perform operation
return 0;
}

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.

Wrong answer displayed for simple math problems c++

I am just starting to learn C++ in college and our first assignment is to make a program that will do basic math. i feel like my code is not mistaken, but when i display the variable "sum", i get an answer that is way off. the value for the answer changes even if i input the same number multiple times. for example, i entered 2 for each variable and i got 1864273973 the first time and 1772335157 the second time. what could be causing this? i am using a macbook pro and code blocks, if anyone is wondering. i have also included my code.
#include <iostream>
#include <stdlib.h>
#include <math.h>
using namespace std;
int main()
{
//variabe declarations
int number, number2;
int sum, difference, product, dividend;
//calculations
sum = number + number2;
difference = number - number2;
product = number * number2;
dividend = number/number2;
//user inputs
cout << "\n1 of 2: Enter a number: ";
cin >> number;
cout << "\n2 of 2: Enter second number :";
cin >> number2;
cout << "\nNumber 1 entered: " << number << "\nNumber 2 entered: " << number2;
//output
cout << "\n" << number << "+" << number2 << "=" << sum << "\n";
}
C++ and almost every language nowadays use a structured system. It reads from top to bottom, so if you say "a = b+c" and then cin >> a, the calculation from b+c will be lost after the new input.
You are trying to calculate using variables that are declared but not initialized. In c++, this will cause the new variable to just receive "trash", a number you probably don't want. To correct this, I think you want to actually receive number and number2 BEFORE doing the math.

c++ how to have a user input equation to be evaluated

My program is meant to ask a user to input an equation. Then find the maximum over an interval given by the user. When I compile my program, the output I get is:
Please complete the equation to be evaluated f(x)=
Please enter the first number of the interval to be checked:
Please enter the last number of the interval to be checked:
Please enter the desired initial step size:
sh: PAUSE: command not found
with the last line repeating many times.
I think the problem here has something to do with having the user input the equation to be tested. However, I'm unsure of how to fix this.
Here's my code
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int main()
{
int a, b, delta, fx, x, y;
int max = 0;
cout <<"Please complete the equation to be evaluated f(x)= " << endl;
cin >> fx;
cout <<"Please enter the first number of the interval to be checked: " << endl;
cin >> a;
cout << "Please enter the last number of the interval to be checked: " << endl;
cin >> b;
cout << "Please enter the desired initial step size: " << endl;
cin >> delta;
for(x = a; x <= b; x = x+delta)
{
y = fx;
if (y > max)
{
max = y;
cout <<"The maximum over the interval from " << a <<"to " << b <<"is " << delta;
}
else
{
delta= delta/2;
}
if (delta < pow( 10, -6))
{
system ("PAUSE");
}
}
return 0;
}
F(x) shouldn't be an integer variable, it should be a string variable. That way, the user can enter operators as characters instead of the compiler thinking they should be numbers. You would then have to process the string to determine the equation; this would require some thought, and possibly a more advanced data structure such as a binary tree.
Simply don't use system("pause"); in the if statement and you'll lose that error:
"sh: PAUSE: command not found". Place it right before the end of the main.
system("pause");
return 0;
As pointed out by others, the form of f(x) could be an issue with the above code.
Consider to redesign what to achieve for your program. One possibility is to narrow down the f(x) as polynomial function so that you can avoid parsing general algebraic equation, in this case you can ask:
how many degree of the polynomial ? upon this, it is followed by input the coefficient value for each factor in the polynomial equation.
This way, you can still use integer (or double - better) in the program.

C++ Functions and Passing Variables [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
C++ passing variables in from one Function to the Next.
The Program is working but when it comes to getUserData it asks for the same information 4 times and then displays the results with negative numbers. I used test numbers for number of rooms 1, 110 for sqrt feet in the room, 15.00 for cost of paint.
//Problems with this not working
void showMenu();
void getUserData(int &, double &, int &);
void doEstimate(int &, double &, int &, double &, double &);
void showReport();
int main()
{
int choice;
//I am not sure why I have to do this but someone suggested to do it and the program complied when I did this int calc ect
int calcGallonsOfPaint, rooms, totalsqrtfeet;
double calcCostOfPaint, costOfPaint;
int calcHoursOfLabor;
double calcLaborCost;
double calcPaintJobCost;
// Set up numeric output formatting.
cout << fixed << showpoint << setprecision(2);
do
{
// Display the menu and get the user's choice.
showMenu();
cin >> choice;
// Validate the menu selection.
while (choice < 1 || choice > 2)
{
cout << "Please enter 1 or 2: ";
cin >> choice;
}
if (choice == 1)
{
//for some reason it just keeps repeating the function getUserData
getUserData(rooms, costOfPaint, totalsqrtfeet);
doEstimate(calcGallonsOfPaint, calcCostOfPaint, calcHoursOfLabor, calcLaborCost, calcPaintJobCost);
showReport();
}
} while (choice != 2);
return 0;
}
void getUserData(int &rooms, double &costOfPaint, int &totalsqrtfeet)
{
int sqrtfeet;
int count = 0;
cout << "Please enter the number of rooms to be painted: ";
cin >> rooms;
cout << "Please enter square feet of wall space in each room: ";
cin >> sqrtfeet;
for (count = 1; count <= rooms; count++)
{
cout << "Please eneter square feet of wall space in room " << count << ": ";
cin >> sqrtfeet;
totalsqrtfeet += sqrtfeet;
}
cout << "What is the cost of the paint: ";
cin >> costOfPaint;
system("cls");
system("pause");
}
void doEstimate(int &calcGallonsOfPaint, double &calcCostOfPaint, int &calcHoursOfLabor, double &calcLaborCost, double &calcPaintJobCost)
{
//I am not sure why I have to do this but someone suggested to do it and the program complied when I did this: puting int rooms ect
int rooms, totalsqrtfeet;
double costOfPaint;
getUserData(rooms, costOfPaint, totalsqrtfeet);
calcGallonsOfPaint = 1 * (totalsqrtfeet/110); //Calculates the number of whole gallons of paint required.
calcCostOfPaint = calcGallonsOfPaint * costOfPaint; //Calculates the cost of the paint required.
calcHoursOfLabor = calcGallonsOfPaint * 6; //Calculates the number of whole hours of labor required.
calcLaborCost = calcHoursOfLabor * 15.00; //Calculates the labor charges.
//Calculates the cost of the paint job. This is the sum of the labor charges and the cost of the paint required.
calcPaintJobCost = calcLaborCost + calcCostOfPaint;
/*110 square feet of wall space
one gallon of paint
six hours of labor
$15.00 per hour for labor
*/
}
void showReport()
{
//I am not sure why I have to do this but someone suggested to do it and the program complied when I did this
int calcGallonsOfPaint, rooms, totalsqrtfeet;
double calcCostOfPaint, costOfPaint;
int calcHoursOfLabor;
double calcLaborCost;
double calcPaintJobCost;
getUserData(rooms, costOfPaint, totalsqrtfeet);
doEstimate(calcGallonsOfPaint, calcCostOfPaint, calcHoursOfLabor, calcLaborCost, calcPaintJobCost);
cout << "The number of rooms to be painted: " << rooms << endl;
cout << "The number of whole gallons of paint required: " << calcGallonsOfPaint << endl;
cout << "The hours of labor required: " << calcHoursOfLabor << endl;
cout << "The cost of the paint: " << calcCostOfPaint << endl;
cout << "The labor charges: " << calcLaborCost << endl;
cout << "The total cost of the paint job: " << calcPaintJobCost << endl;
system("pause");
system("cls");
}
One thing that you should do is initialise totalsqrtfeet to zero in your main function. That's because you're just adding the size of each room to it and it starts out with a random value: junk + a + b + c + d is still junk :-)
On top of that, you call getUserData from your main function and then again from doEstimate. And then you call them both again in showReport. That's why it's asking four times. Just call getUserData once. Since it's homework, I'll leave you to figure out where but here's a hint. If you do it in main (nudge, nudge, wink, wink), you'll have to pass he variables into doEstimate as well, not create new variables of the same name within that function and magically expect the compiler to associate them with the originals.
To caveat on what paxdiablo said, you are calling getUserData in your nested while loop, but I don't understand the purpose of calling getUserData(rooms, costOfPaint, totalsqrtfeet); prior to doEstimate(...) when the data isn't used nor passed to doEstimate(...) until you call getUserData again while inside the doEstimate(...) function. You should pass by value the rooms, costOfPaint, and totalsqrtfeet variables to doEstimate(...) or make them global since you only have one main() function anyways. If you had some sort of OO solution, then I wouldn't recommend making them global and rather part of a class.
Also all these variables are ZERO or NULL when they are passed into doEstimate(...):
calcGallonsOfPaint, calcCostOfPaint, calcHoursOfLabor, calcLaborCost, calcPaintJobCost
If you want to output them, then you need to pass them by reference to doEstimate(...) and then when it gets to the cout then it will sufficiently print the correct values. That is why it is zero.
The bottom line is though you need one function to call the other functions. That would be the simplest plan at this point, such as:
GetDataAndPrint(...) {
// Get some data
// Do estimate, pass in values by reference
// Print Results from calculated values
// return
}