Multiplication with floats is wrong for some reason - c++

SOk I edited out all the irrelevant information. Also I did some testing on a new file and it seems when you multiply two numbers that are being put in variables against each other it produces the wrong result. Like in my code the user is entering the length in feet first then in inches. The inches is then divided by 12 and added with feet. Also there getting rounded. Same goes for the width. Then when you multiply the length and width together it produces the wrong result.
Why is that? How do I fix it?
using namespace std;
void setdata();
int main(){
setdata();
return 0;
}
void setdata(){
int idnumber, lengthfeet, lengthinches, widthfeet, widthinches;
float costsqfoot, discount, lengthinchdec, widthinchdec, foot1, reallength, realwidth, arearoom;
foot1= 12;
cout << "What is length of room \t Feet: "; cin >> lengthfeet; cout << "\t \t \t Inches: "; cin >> lengthinches;
cout << "What is width of room \t Feet: "; cin >> widthfeet; cout << "\t \t \t Inches: "; cin >> widthinches;
cout << fixed << setprecision(2);
lengthinchdec = lengthinches / foot1; cout << lengthinchdec << endl; widthinchdec = widthinches / foot1; cout << widthinchdec;
reallength = lengthfeet + lengthinchdec; realwidth = widthfeet + widthinchdec; arearoom = (reallength * realwidth);
cout << endl;
cout << reallength << endl; cout << realwidth << endl;
cout << arearoom;
}
example
input for length feet:30
input for length inch: 5
input for width feet: 18
input for width inch: 11
Output for reallength is 30.42. The lengthinches is being divided by 12 so 5/12 is .42 when rounded up.
Output for realwidth is 18.92. The widthinches is being divided by 12 so 11/12 is .92 when rounded up.
The answer comes out 575.38.
It's supposed to come out 575.54

For your checking on the calculator, you're rounding up the intermediate results.
Your program isn't rounding the intermediate results, only the result of the multiplication.
575.38 is the correct answer!

Imperial units hell :)
multiplied it by hand and got
30 feet 5 inches * 18 feet 11 inches = 82 855 inches2
which is 575.38194444444 sqf
so... what is the problem?
and just for fun formatted the code and pushed it into CoLiRu with all variables set to double instead of float, just in case... http://coliru.stacked-crooked.com/a/2fcef984c5561159 and got the same result

Floating point calculations may be tricky. Values like the result of 5/12 aren't representable by a binary floating point number with a finite number of digits, so they are calculated and stored in float or a double types with a certain amount of rounding errors.
In some cases (like your particular example), one can avoid those errors (even if negligible in practice) using integer arithmetic instead.
Consider this snippet of code and how it deals with your problem:
#include <iostream>
#include <iomanip>
int main() {
using std::cout;
using std::cin;
constexpr int inches_in_one_foot = 12;
constexpr int square_inches_in_one_square_foot =
inches_in_one_foot * inches_in_one_foot;
// Please, note that in real code user input should be checked
int length_feet, length_inches, width_feet, width_inches;
cout << "What is the length of the room?\nFeet: ";
cin >> length_feet;
cout << "Inches: ";
cin >> length_inches;
cout << "What is the width of the room?\nFeet: ";
cin >> width_feet;
cout << "Inches: ";
cin >> width_inches;
// calculate the dimensions in inches
int length = length_inches + inches_in_one_foot * length_feet;
int width = width_inches + inches_in_one_foot * width_feet;
// the area is precisely calculated in square inches
int area = length * width;
int area_feet = area / square_inches_in_one_square_foot;
// note that this ^^^ is an integer division, or: 82855 / 144 = 575
int area_inches = area - area_feet * square_inches_in_one_square_foot;
cout << "\nArea: " << area_feet << " square feet and "
<< area_inches << " square inches.\n";
cout << "or : " << std::fixed << std::setprecision(2)
<< static_cast<float>(area) / square_inches_in_one_square_foot
<< " square feet.\n";
return 0;
}
Entering the values 30 5 18 11, it gaves the following output:
Area: 575 square feet and 55 square inches.
or : 575.38 square feet.
Note that in the second result, the decimal part doesn't represent 38 square inches, but 0.38 square feet, as a two figures approximation of the value 0.381944.

Related

What's wrong with this simple piece of code? [duplicate]

This question already has answers here:
Why not use Double or Float to represent currency?
(16 answers)
Closed 3 years ago.
The code seems to work fine when it performs the first step of multiplying the number of quarters entered by 0.25, but then it just doesn't work with the next two steps.
#include <iostream>
using namespace std;
int main()
{
int quarter, dime, nickle;
int result;
quarter = 25;
dime = 10;
nickle = 5;
int numQuarters, numDimes, numNickles;
cout << "Please enter the number of quarters and press Enter: ";
cin >> numQuarters;
cout << "Please enter the number of dimes and press Enter: ";
cin >> numDimes;
cout << "Please enter the number of nickles and press Enter: ";
cin >> numNickles;
result = (numQuarters * quarter) + (numNickles * nickle) + (numDimes * dime);
cout << "The total amount of pennies is: " << result;
return 0;
}
I expect the output of 4 quarters, 10 dimes & 20 nickels to be 300 pennies
The output is 102
Edit: Code Fixed and working now!
Hmm... your code seems fine, but I think something was wrong with the Order of Operations in your Math. I just changed the value of nickel to 0.05 and the value of dime to 0.10 (I think that was a mistake in your code). I aslo moved the *100 down to the cout statement, and that helped clear things up...
#include <iostream>
using namespace std;
int main()
{
float quarter, dime, nickle, penny;
float result;
quarter = 0.25;
dime = 0.10;
nickle = 0.05;
float numQuarters, numDimes, numNickles;
cout << "Please enter the number of quarters and press Enter: ";
cin >> numQuarters;
cout << "Please enter the number of nickles and press Enter: ";
cin >> numNickles;
cout << "Please enter the number of dimes and press Enter: ";
cin >> numDimes;
result = (numQuarters * quarter) + (numNickles * nickle)+ (numDimes * dime);
cout << "The total amount of pennies is: " << result * 100;
return 0;
}
Oh, and just like what #Pete Becker said, do your calculations in pennies (whole numbers). Not only does it fix some minor errors with floats as money, it also makes your code easier to read and manipulate.

Length conversion program cannot convert decimal number in C++

I have to write a program that takes length as input in feet and inches and the program should then convert the lengths in centimeters and display it on screen. So this is my code:
#include "pch.h"
#include <iostream>
using namespace std;
int main()
{
double totalinches;
double centimeter;
float inch_to_centimeter = 2.54f;
int feet_to_inch = 12;
int feet;
int inch;
cout << "Enter the length in feet:";
cin >> feet;
cout << "Enter the length in inches:\n ";
cin >> inch;
totalinches = (feet * feet_to_inch) + inch;
cout << "Total length in inches:\n ";
cout << totalinches;
centimeter = totalinches * (inch_to_centimeter);
cout << "The number of centimeter= ";
cout << centimeter;
When I run the code, the code can only calculate natural number (non-decimal number) but whenever I type decimal number, the code is error. This is the error that I got when I type decimal number. The code itself skip the "Enter the length in inches" and the result is always 60 and 152.4. Sorry for my bad English and i am new to code.
Enter the length in feet:5.74
Enter the length in inches:
Total length in inches:
60The number of centimeter= 152.4
C:\Dev\C++\HomeWork\Debug\HomeWork.exe (process 22468) exited with code 0.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .

Why is my C++ program outputting a different number for conversion of meters to feet?

So i am writing a C++ program to convert meters to feet. The program does compline. However, when i set the value of feet = 3.279 and entered 3.25 for meters. The answer comes back as 9.837. Can someone tell me why this may be happening?
(code below)
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int meters;
int feet;
feet = 3.279 * meters;
cout << "Enter Meters to be converted to feet: ";
cin >> meters;
cout << meters * 3.279 << " feet " << endl;
}
Integers are whole numbers. When a non-whole number is assigned to an integer in C++ everything past the decimal is ignored.
int x = 1.123; // x = 1
int y = 1.999; // y = 1
Furthermore, this program uses meters before it has been assigned a value on the following line
feet = 3.279 * meters;
But feet is also never used after this assignment.
The only portion of code that is really being used is
cin >> meters;
cout << meters * 3.279 << " feet " << endl;
When you input 3.25 for meters the value as an integer becomes 3. The calculation on the following line therefore becomes 3 * 3.279 which does in fact equal 9.837.

Trying to calculate jacket, hat, and waist size for assignment. Output is "0x8049f64" instead of answer

I'm getting some odd outputs when running this program. Any suggestions? Pardon the mess. Typed it up in a hurry. This is the guidelines for the assignment.
Write a program that asks for the user’s height, weight, and age, and
then computesclothing sizes according to the formulas:
1.Hat size = weight in pounds divided by height in inches and all multiplied by 2.9
2.Jacket size (chest in inches) = height times weight divided by 288 and then adjusted by adding 1/8 of an inch for each 10 years over the age of 30. (Note that the adjustment only takes place after a full 10 years. Thus, there is no adjustment for ages 30 through 39, but 1/8 of an inch is added for age 40.)
3.Waist in inches=weight divided by 5.7 and then adjusted by adding 1/10 of an inch for each 2 years over age 28. (Note that the adjustment only takes place
after a full 2 years. Thus, there is no adjustment for age 29, but 1/10 of an inch is added for age 30.)
#include <iostream>
using namespace std;
double hat(double,double);
double jacket(double,double,int);
double waist(double,double,int);
int main ()
{
double height, weight;
int age;
char answer;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
do
{
cout<< "Enter the customer's height in inches: ";
cin>>height;
cout<< "Enter the customer's weight in pounds: ";
cin>>weight;
cout<< "Enter the customer's age: ";
cin>>age;
cout << cout<< "\tYour Hat size: " << cout << "\tYour Jacket size: "< cout << "\tYour Waist size: "<< cout<< "Would you like to continue (y/n)? ";
cin>>answer;
}while(toupper(answer) == 'Y');
return 0;
}
double hat(double weight ,double height)
{
return ((weight/height) * 2.9);
}
double jacket(double height,double weight,int age)
{
double size;
int j;
if (age>=30)
{
if((age % 10) !=0)
age = age-(age%10);
j= (age-30)/10;
size =((height * weight) / 288)+((1.0/8)*j);
}
else
size =((height * weight) / 288);
return size;
}
double waist(double height,double weight,int age)
{
double size2;
int k;
if(age >= 28)
{
if((age % 2) !=0)
age = age-(age%2);
k = (age-28)/2;
size2 = (weight/(5.7))+( (1.0/10)*k);
}
else
size2 = weight / (5.7);
return size2;
}
Your final cout << line in the do loop is piping cout to cout, instead of your answer to cout. Not to mention there's a < in there after jacket size instead of a <<
cout << cout<< "\tYour Hat size: " << cout << "\tYour Jacket size: "< cout << "\tYour Waist size: "<< cout<< "Would you like to continue (y/n)? ";
You never even tried to do the calculation, so you have no answer to print.
Instead I see a lot of cout << cout in your code. Trying to print cout itself doesn't turn out well. What happens is that iostreams don't know how to print an output stream, however in old versions of C++, cout has an implicit conversion to a pointer, and a stream knows how to display that. So you are seeing the pointer equivalent to cout.
You should enable C++11 (or later) support in your compiler. Then cout won't have an implicit conversion to void*, and the compiler will detect mistakes like this.
you just need to replace your cout line with this line of code
cout<< "\tYour Hat size: " << hat(weight ,height) << "\tYour Jacket size: "<< jacket( height, weight, age) << "\tYour Waist size: "<< waist( height, weight, age)<< "\n \nWould you like to continue (y/n)? ";

Calculation Problem C++

I'm really new to C++, and this is homework. I don't understand what's going on. When I run this, everything works fine if I put in 60000 for current salary and .05 for pay increase, but if I put in something like 52000 for current salary and .23 for pay increase, then the retroactive pay comes out as 5982.00 instead of 5980.00. Is it something to do with the decimals or something? I don't really know. Thanks in advance.
// Variables
char fullName[30]; // The user's full name - INPUT
int currentAnnual; // The users's current annual salary - INPUT
float percentIncrease; // The percent increase due on the
// current annual salary - INPUT
// The retroactive pay
float retroactive;
// The new monthly salary based on the pay increase and the new salary
float monthlySalary;
// The new salary the user should receive based on their old salary
// and their pay increase
float newSalary;
for(int lcv = 1; lcv <= 3; lcv++)
{
// INPUT
cout << "What is your full name? ";
cin.getline(fullName, 30);
cout << "What is your current salary? ";
cin >> currentAnnual;
cout << "What is your pay increase (please input percentage in"
"decimal format)? ";
cin >> percentIncrease;
// PROCESSING
newSalary = (currentAnnual * percentIncrease) + currentAnnual;
monthlySalary = newSalary / 12;
retroactive = (monthlySalary - (currentAnnual / 12)) * 6;
// OUTPUT
cout << endl;
cout << fullName << "'s Salary Information\n";
cout << left << setw(15) << "New Salary" << setw(19) << "Monthly Salary"
<< "Retroactive Pay\n";
cout << setprecision(2);
cout << fixed;
cout << right << setw(10) << newSalary << setw(19) << monthlySalary
<< setw(20) << retroactive << endl << endl;
cout << "<Press enter to continue>";
cin.ignore(100, '\n');
cin.ignore(1000, '\n');
cout << endl;
}
currentAnnual / 12
The division of two integers in C is an "integer division" (it gives an integer), and I think you dont want that. One solution is to change it to currentAnnual / 12.0. Anyway, it's important that you understand what is happening here.
Change currentAnnual / 12 to currentAnnual / 12.0 to force a floating-point calculation to be done. Otherwise, that part of the computation will be rounded off to the nearest integer below.
You should do monthlySalary = newSalary / 12.0; instead of monthlySalary = newSalary / 12;
so you have to specify that you want to divide on float number. Otherwise result will be integer. For example 125./12 = 10 but 125./12. = 10.41(6). And of course you get wrong results.
Try to add .0 or just . to all your constants.
Floating point calculations are not as accurate as you might expect. Try replacing float with double in the above code (double is a "double-precision floating-point number"; it can store many more values than a float, and is much more accurate).
Also, order of operations is sometimes significant, so you may want to re-order the retroactive calculation to something like
6 * monthlySalery - currentAnnual / 0.5;
and try other combinations to see what works best.