C++ Simple Farenheit Conversion - c++

I am trying to create a simple program that takes a value Celsius entered by the user, and converts it to Fahrenheit.
#include <iostream>
using namespace std;
int main()
{
float celsius, farenheit;
cout << "Enter a temperature in farenheit ";
cin >> farenheit;
celsius = (farenheit - 32) * (5 / 9);
cout << celsius;
return 0;
}
It always prints a value of 0, why is this?

This is because you multiply by 5 / 9, which is zero due to integer division.
If you change parentheses like this
celsius = ((farenheit - 32) * 5) / 9;
you would get the correct result.
Since you parenthesized (5 / 9), the compiler computed that value before performing multiplication. Since (5 / 9) is an integer expression, the compiler performs an integer division, meaning that the fractional part is discarded. As the result, all proper fractions become zeros.
Another way to fix this problem is to force C++ to use floating point division by making one or both numbers a floating point constant (specifically, a constant of type double) by appending .0 to them, for example:
celsius = (farenheit - 32) * (5.0 / 9);

Related

setprecision(2) value not working in if statement even when the conditions are true [duplicate]

This question already has answers here:
What is the behavior of integer division?
(6 answers)
Division of two numbers always returns an integer value
(3 answers)
Closed 3 months ago.
I dont understand why setprecision(2) not working when using if else statement
I tried doing this and it displays the else statement. I dont see any problem, maybe im using setprecision() wrong? I even displayed the quotient to prove that the if statement should be the one running.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float x = 2;
float y = 3;
float quotient, answer;
quotient = x / y;
cout << fixed << setprecision(2);
cout << quotient << " (is the answer)\n";
cout << " What is " << x << " divided by " << y << " ? ";
cin >> answer; // answer should be 0.67
if (quotient == answer)
cout << " You got the right answer! ";
else
cout << " Nice Try :( ";
return 0;
}
The line
quotient = x / y;
will assign the value of 0.0 to the variable quotient, because 2/3 is 0, using the rules of integer division. Therefore, if the user enters 0.67, this value will not compare equal to 0.0.
If you want the division 2/3 to evaluate to something like 0.6666666667, then you must make at least one of the operands a floating-point number, for example by using a cast:
quotient = static_cast<float>(x) / y;
However, even if you did this, your comparison would still not work, because the expression
cout << fixed << setprecision(2) << quotient;
will only change the way the variable quotient is printed. It will not change the actual value of the variable.
In order to round the actual value of the variable, you can use the function std::round. Note that this will only round to the nearest integer, so if you want to round to the nearest multiple of 0.01, then you will first have to multiply the number by 100 before performing the rounding operation. If you want, you can then divide the number by 100 again, to get the original number again, rounded to the nearest multiple of 0.01.
However, you should be aware that these operations may introduce slight floating-point inaccuracies. For this reason, it may be better to not require an exact match in the comparison
if (quotient == answer)
but to consider a deviation of up to 0.01 to still be considered a match. You can do this for example by changing the expression to this:
if ( std::abs( quotient - answer ) < 0.01 )
Note that you will have to #include <cmath> in order to use std::round and std::abs.

C++ multiply float by fraction

just started C++ from a MATLAB background and getting confused.
float farenheit, celcius;
cin >> farenheit;
celcius = (farenheit - 32) * (5 / 9);
cout << "Temperature (c): " << celcius;
why does multiplying by 5/9 not work as expected, but this does?:
float farenheit, celcius;
cin >> farenheit;
celcius = ((farenheit - 32) * 5) / 9);
cout << "Temperature (c): " << celcius;
Thanks!
Thanks everyone,
C++ interprets 5 and 9 as int values so 5/9 is also an int.
5/9 = 0.566 which is truncated down to 0.
To fix this, append .0 or .f to the values be interpreted as a double or float respectively.
C++ considers 5 and 9 to be integers and the division is integer division, which means 5/9 = 0 (it returns the quotient).
So use 5.0 and 9.0 if you want them to be floating points.

C++ numbers aren't rounding correctly

I am new to Stack Overflow, and programming in general. I am in a few classes for programming C++ and have come across an assignment I am having a bit of trouble with. This program is supposed to take fahrenheit and convert it to celsius. I have seen other programs, but could not find a duplicate to my particular problem. This is my code.
#include <iostream>
using namespace std;
int main()
{
int fahrenheit;
cout << "Please enter Fahrenheit degrees: ";
cin >> fahrenheit;
int celsius = 5.0 / 9 * (fahrenheit - 32.0);
cout << "Celsius: " << celsius << endl;
return 0;
}
So this is working great on 4 of the 5 tests that are run. It rounds 22.22 to 22 and 4.44 to 4 like it should, but when 0 F is put in, it rounds -17.77 to -17 instead of -18. I have been researching for about an hour and would love some help! Thank you.
Use std::round() instead of relying on the implicit conversion from double to int. Either that, or do not use conversion at all, show the temperature as a double.
EDIT: As others already pointed out, implicit conversion will not round but truncate the number instead (simply cut off everything after the decimal point).
Integers round down implicitly, as do casts to integer types.
Most likely, using a float in place of an int would give the most sane results:
#include <iostream>
using namespace std;
int main()
{
int fahrenheit;
cout << "Please enter Fahrenheit degrees: ";
cin >> fahrenheit;
float celsius = 5.0 / 9 * (fahrenheit - 32.0);
cout << "Celsius: " << celsius << endl;
return 0;
}
To get normal-looking output (fixed-point like "14.25", not scientific with e notation), pass std::fixed to cout before printing the floating point. You can also use cout.precision() to set the number of digits you would like in the output.
If for some other reason you need an int, use std::round() around the right hand of the expression.
When the compiler converts a floating point number to an integer, it doesn't round, it truncates. I.e. it simply cuts of the digits after the decimal point. So your program behaves as it is programmed to do.
int x = 3.99;
int y = std::round(3.99);
std::cout
<< "x = " << x << std::endl
<< "y = " << y << std::endl
;
-->
x = 3
y = 4
C/C++ is not doing floating point round when static_cast<int>-ing a float to an int. If you want to round, you need to call library function std::round()

c++ currency converter trailing zeroes

i just started programming and wrote a currency converter programme that needs to be accurate to 2 decimals (using double) However i would not like trailing zeroes but users should still be able to input decimals with set precision rounding it off to a whole integer
Here is the code:
#include <iostream>
#include <iomanip>
using namespace std;
const double DOLLAR = 0.05917;
const double EUROS = 0.05681;
int main()
{
double rand;
double equivD;
double equivE;
cout << setprecision(2)<<fixed;
cout << " Enter Rand amount: ";
cin >> rand;
cout << rand << " Rand(s)= ";
equivD= (rand*DOLLAR);
cout << equivD<< " Dollar(s)\n ";
cout << rand << " Rand(s)= ";
equivE= (rand*EUROS);
cout << equivE<< " Euro(s)\n ";
return 0;
}
Output if entered value is a 1000 is:
1000.00= 57.24 Dollars
1000.00= answer
If an integer is inputed without decimals I would like to remove the .00 but still keep it as a double in case a decimal is inputed. How do I do this?
Don't use floating point for money: you'll be off on the 15th significant figure; which, by the time you've consumed two digits for the cents, is not particularly large.
In your case, use a 64 bit integral type and work in cents, tweaking your formatting when you want to display computed values. (Don't forget to round correctly when using the FX rates).
If you want different formatting for different cases, I would test to see if there is a decimal.
In your example, with doubles, this could be
if( 0 == (((long long)(rand*100)) % 100) )
cout << setprecision(0);
This multiplies rand by 100, converts it to an integral type, and then checks if the right two digits are both zero.
The Better Solution
Use an integral type (like int or long long) to store the value as "hundredths of rands" (like Bathsheba suggested). This reduces rounding errors. To test for the decimal and output, just use a modulo, like this:
cout << (rand / 100); // Integer division
if( 0 != (rand % 100) ) // Are there any amounts less than one rand?
cout << '.' << (rand % 100);
Of course, there is still the issue of reading in the user input to a long long, but I'm not an expert with cin.

Arithmetic expression is 0 instead of 1 [duplicate]

This question already has an answer here:
Integer division always zero [duplicate]
(1 answer)
Closed 7 years ago.
#include <iostream>
using namespace std;
int main() {
int a,b,c;
cin >> a >> b >> c;
cout << a/b*c;
return 0;
}
For a=5 b=10 c=2 the output gives 0 which is obviously wrong.
As far as I understood << / * are binary operators / and * "bond" stronger than << and for / and * it is calculated from the left to right so first 5 is devided by 10, then the result (0.5) is multiplicated with 2 which is 1 and that is delivered by << to cout.
So can anyone give me an explanation for that result (0)?
This is the integer division issue: if a==5 and b==10, then a/b==0.
See the standard, Multiplicative operators [expr.mul]
For
integral operands the / operator yields the algebraic quotient with any fractional part discarded
This is the result of integer rounding. When integer division is performed any fractional remainder is simply cut off. So 2 / 3 == 0.
To keep the results as accurate convert use doubles or convert the variables to doubles in the expression. So something like this
static_cast<int>(static_cast<double>(a) / static_cast<double>(b) * static_cast<double>(c))
will result in the correct value.
No its not wrong
Since all variables are integers.
5/10 is 0 in the integer world and that multiplied with 2 is still 0
9/10 is also 0 but 11/10 is 1
if you want something useful from this declare the variables as double instead or IOW:
int main() {
double a,b,c;
cin >> a >> b >> c;
cout << a/b*c;
return 0;
}