C++ multiply float by fraction - c++

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.

Related

C++ - Where in my code should I include static_cast?

My static_cast does not seem to be working. I create 5 int variables at the beginning of my code and attempt to change one (the total) to a double after performing calculations on the other 4, but it keeps displaying the int.
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
int main ()
{
int grade1, grade2, grade3, grade4, avg;
cout << "Please input four grades: " << endl;
cin >> grade1;
cin >> grade2;
cin >> grade3;
cin >> grade4;
avg = (grade1 + grade2 + grade3 + grade4) / 4;
cout << "Grades: " << grade1 << ", " << grade2 << ", " << grade3 << ", " << grade4 << endl;
cout << "\n";
cout << "Average grade: " << static_cast<double>(avg) << endl;
return 0;
}
When you are combining the integers and assigning them to avg.
You already have integer rounding conversion, so you need to static cast before you assign the number to the avg result.
You also don't even need to use static cast as long as you divide by 4.0 and make avg a double.
Example:
double avg = static_cast<double>(grade1+grade2+grade3+grade4) / 4.0;
// Alternative without static that still works
double avg = (grade1+grade2+grade3+grade4) / 4.0;
I would suggest that the literal answer to your question "Where in my code should I include static_cast?" is quite simple: nowhere, if at all possible.
static_cast - like all the C++ _cast operators, and all explicit (C-style) typecasts should be avoided wherever possible. They have their uses, but it is better to minimise their usage, and certainly to avoid using them as blunt instruments to fix problems in code.
In your case, the correct results can be obtained quite simply by using appropriate types of variables, and any literal values having a suitable type.
Firstly, avg needs to be of type double. This involves changing
int grade1, grade2, grade3, grade4, avg;
to
int grade1, grade2, grade3, grade4;
double avg;
Second, the calculation of the value of avg needs to be changed so it doesn't do an integer division. This means changing
avg = (grade1 + grade2 + grade3 + grade4) / 4;
(which doesn't work because grade1, ... grade4 are all of type int, their sum is an int, the literal 4 is an int, and dividing two ints produces an int) to
avg = (grade1 + grade2 + grade3 + grade4) / 4.0; // note the 4.0
This works, because the literal 4.0 has type double. The value (grade1 + grade2 + grade3 + grade4) is calculated as an int but, because it is being divided by a double, that integral value is converted implicitly to double before performing the division - and the result is of type double.
This is the only place in which I would consider using a static_cast here, by converting the 4 to a double.
avg = (grade1 + grade2 + grade3 + grade4) / static_cast<double>(4);
which has the same net effect as the previous calculation of avg. In your code, it makes little difference. But a static_cast can be useful here in more general-purpose code, for example, if the number of input values (grade1, grade2, etc) is calculated as an integral value (e.g. the number of elements in an array).
The third thing you can do is remove the static_cast from the statement that outputs avg since it is now redundant (converting a double to double has no effect). In other words turn
cout << "Average grade: " << static_cast<double>(avg) << endl;
to
cout << "Average grade: " << avg << endl;
There are two issues in your code.
The first is that you declared avg as int, so the result is going to be rounded as int always.
However, declaring avg as double will not solve your problem immediately. In C++, operators are executed on objects of the same type and the result is an object of the same type.
(grade1 + grade2 + grade3 + grade4) is an int and 4 is an int, therefore the result will be an int. It doesn't matter if later is implicitly or explicitly casted to double, you will still get a rounded result.
In case the operands are not the same type, the compiler will implicitly promote one to match the other. The following lines will give you the correct result:
static_cast<double>(grade1 + grade2 + grade3 + grade4) / 4;
(grade1 + grade2 + grade3 + grade4) / 4.0;
static_cast<double>(grade1 + grade2 + grade3 + grade4) / 4.0;
An int cannot hold decimal places. int / results in an int, there are no decimals that result. You need to use the correct /, i.e at least one of the operands must be double to get a double result.
#include <iostream>
int main () {
std::cout<<"Please input four grades: "<<std::endl;
int grade1, grade2, grade3, grade4;
std::cin>>grade1;
std::cin>>grade2;
std::cin>>grade3;
std::cin>>grade4;
double avg=static_cast<double>(grade1+grade2+grade3+grade4)/4;
std::cout<<"Grades: "<<grade1<<", "<<grade2<<", "<<grade3<<", "<<grade4<<std::endl<<std::endl;
std::cout<<"Average grade: "<<avg<<std::endl;
}
You don't need the static cast here, as you can change the int literal 4 to a double literal 4.0, but if you are summing the elements of a vector then calling size() on it, that will be an integer, and you will have to cast somewhere.

double, float, {0.0}, {0.0f}, what's the big deal?

So I wrote this small practice program that tells you how many nickels and cents you would need for the amount given. I don't undersand why the program outputs 0 for cents even the the math is correct. I can't seam to understand what the issue is.
// Example program
#include <iostream>
using namespace std;
int main()
{
const double nickels{0.05};
const double cents{0.01};
int amt_needed_nickels{0}, amt_needed_cents{0};
double amt_val{0.06f}; // for 0.06 cents
double amt_val_copy{amt_val};
amt_needed_nickels = amt_val / nickels;
if(amt_needed_nickels != 0)
amt_val -= (nickels * amt_needed_nickels);
amt_needed_cents = amt_val / cents;
cout << "If it costs $" << amt_val_copy << ", you'll need:\nNickels: " << amt_needed_nickels << "\nCents: " << amt_needed_cents << "\n";
cout << "Even though amt_val is " << amt_val << ", and cents is also " << cents << ", and 0.01/0.01 does equal 1, why is amt_needed_cents not 1?\n";
}
To be fair I know if i change the const double cents{0.01} to const float cents{0.01}, and remove the f from double amt_val{0.06f}; to double amt_val{0.06}; it will work, but i fail to understand what's really going on beneath the surface. Why does the program give 0 to amt_needed_cents above, and 1 in the other cenario?
// Example program
#include <iostream>
using namespace std;
int main()
{
const double nickels{0.05};
const float cents{0.01};
int amt_needed_nickels{0}, amt_needed_cents{0};
double amt_val{0.06}; // for 0.06 cents
double amt_val_copy{amt_val};
amt_needed_nickels = amt_val / nickels;
if(amt_needed_nickels != 0)
amt_val -= (nickels * amt_needed_nickels);
amt_needed_cents = amt_val / cents;
cout << "If it costs $" << amt_val_copy << ", you'll need:\nNickels: " << amt_needed_nickels << "\nCents: " << amt_needed_cents << "\n";
cout << "I know this is correct, but I don't know what the compiler is thinking with this as compared to the other\n\n";
}
Floating point calculations are not precise, when doing math you get the very small difference, which will break your program if you try to check for an exact equality of the numbers. For example, 1.2 * 3 is not exactly 3.6 (note that this doesn't mean all calculations are inexact: e.g. multiplication by any power of 2 is always exact: things like 1.5 * 2 and 1.1 / 4 always give the best answer possible). This is because decimal fractions like 1/10 and 1/100 are not exactly representable in binary, which is an issue when our coins are based on 1/100 (the cent).
In your program, you should instead represent coins as an integers by converting all values to cents, then everything will work just fine. That is, you know that the largest denominator you will ever deal with is 100, so you may as well multiply everything by 100. So, nickels is going to be 5, cents is going to be 1 and all calculations will be precise.
To avoid any confusion, here's your code in integers:
int dollars = 100, nickels = 5, cents = 1;
int amt_needed_dollars = amt_val / dollars;
amt_val -= amt_needed_dollars * dollars;
int amt_needed_nickels = amt_val / nickels;
amt_val -= amt_needed_nickels * nickels;
// skipped dividing by cents, because it's '1' anyway
int amt_needed_cents = amt_val;
Float: A floating point number. It's a single-precision 32bit number. More common.
Double: Like the name it holds "double" the value of a float. It's a double-precision 64bit number. It's more precise and can hold way more decimal points.
I'm not the best with c++ but it looks like the problem is here:
int amt_needed_nickels{0}, amt_needed_cents{0};
amt_needed_nickels = amt_val / nickels;
Try changing amt_needed_cents to a float or double the parsing/rounding it later. Unlike other languages (like JS) c++ is annoying when trying to convert types like that. You are dividing two floats to an int which probably truncates the decimal.

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

for loop help. Terminates when it isnt supposed to. c++

I'm new to stackoverflow, but i did try to look for an answer and could not find it. I also can't seem to figure it out myself. So for a school C++ project, we need to find the area under a curve. I have all the formulas hardcoded in, so don't worry about that. And so the program is supposed to give a higher precision answer with a higher value for (n). But it seems that when I put a value for (n) thats higher than (b), the program just loops a 0 and does not terminate. Could you guys help me please. Thank you. Heres the code:
/* David */
#include <iostream>
using namespace std;
int main()
{
cout << "Please Enter Lower Limit: " << endl;
int a;
cin >> a;
cout << "Please Enter Upper Limit: " << endl;
int b;
cin >> b;
cout << "Please Enter Sub Intervals: " << endl;
int n;
cin >> n;
double Dx = (b - a) / n;
double A = 0;
double X = a;
for (X = a; X <= (b - Dx); X += Dx)
{
A = A + (X*X*Dx);
X = X * Dx;
cout << A << endl;
}
cout << "The area under the curve is: " << A << endl;
return 0;
}
a, b, n are integers. So the following:
(b - a) / n
is probably 0. You can replace it with:
double(b - a) / n
Since all the variables in (b - a) / n are int, you're doing integer division, which discards fractions in the result. Assigning to a double doesn't change this.
You should convert at least one of the variables to double so that you'll get a floating point result with the fractions retained:
double Dx = (b - a) / (double)n;
The other answers are correct. Your problem is probably integer division. You have to cast on of the operands to double.
But you should use static_cast<> instead of C-style casts. Namely use
static_cast<double>(b - a) / n
instead of double(b - a) / n or ((double) (b - a)) / n.
You are performing integer division. Integer division will only return whole numbers by cutting off the decimal:
3/2 == 1 //Because 1.5 will get cut to 1
3/3 == 1
3/4 == 0 //Because 0.5 will get cut to 0
You need to have at least one of the two values on the left or right of the "/" be a decimal type.
3 / 2.0f == 1.5f
3.0f / 2 == 1.5f
3.0f / 2.0f == 1.5f

C++ Simple Farenheit Conversion

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