c++ type cast an arithmetic operation - c++

#include <iostream>
int main()
{
long long w_popn;
long long us_popn;
std::cout << "Enter the world's population: ";
std::cin >> w_popn;
std::cout << "Enter the population of the US: ";
std::cin >> us_popn;
std::cout << "The population of the US is " << float (us_popn/w_popn) << "% of the world population" << std::endl;
return 0;
}
I am currently doing some exercise questions from c++ primer plus, and I am stuck at the very last print statement in my code. Particularly the part where I type float (us_popn/w_popn). Is there a quick and dirty way of turning the results into a floating number in the cout statement without having to manually store the results in a float variable? I ask this because it seems that putting a typecast of float in front of the integer division in a cout statement doesn't seem to affect it and I end up getting 0 as a result of truncation.

You have to cast the operands before the division, otherwise you will be casting the result:
static_cast<float>(us_popn)/static_cast<float>(w_popn)

Related

Turbo C++ Result not coming ok with long int

I am facing issue with result output with long int. Here Below is my Program, I am calculating tax with various methods 1) taking result output in int and long variable. I think all the four results in my code should be the same, but result output in tax3 variable is coming different (less by 1) than other three. please help me to understand the reason.
#include<iostream.h>
#include<conio.h>
int main()
{
long salary;
cout << "Enter Salary: " << endl;
cin>>salary;
float tax1, tax2;
long tax3, tax4;
tax1 = salary*0.15;
tax2 = (salary*15)/100;
tax3 = salary*0.15;
tax4 = (salary*15)/100;
cout << "tax1=" << tax1 << endl;
cout << "tax2=" << tax2 << endl;
cout << "tax3=" << tax3 << endl;
cout << "tax4=" << tax4 << endl;
getch();
return(0);
}
There are two major types of numbers which are known by the compiler - floating points and Integers. The floating points follows IEEE-754 floating point for representation for 32 bit(float) and 64 bit(double). In turbo C the int is only 16 bits. Also when you copy from float to int only integer part is copied. i.e. consider the following example :
float a=9.8;
int b=(int)a;
In above code when you print b it will give only 9. Also a piece of advice for you, if you want to learn c++ better then please switch from turbo c to gcc.

Calculate using int and output float?

//findSlope(twoPoints).exe
//finding the slope of line AB, using coordiantes of point A and B.
#include <iostream>
int main()
{
int a, b, c, d;
float answer;
std::cout << "The X coordiante of A: ";
std::cin >> a;
std::cout << "\nThe Y coordiante of A: ";
std::cin >> b;
std::cout << "\nThe X coordiante of B: ";
std::cin >> c;
std::cout << "\nThe Y coordiante of B: ";
std::cin >> d;
std::cout << "\nThe slope of line AB = " << std::endl;
answer = (b-d)/(a-c);
std::cout.setf(std::ios::fixed);
std::cout.precision(3);
std::cout << answer << std::endl;
//alternative= std::cout << fixed << setprecision(#) << answer << std::endl;
std::cout.unsetf(std::ios::fixed);
return 0;
}
I am learning C++ and I tried to code a program that calculate the slope using the coordinates of two points.
I understand that if I use float for variables I declared for the coordinates, the result of the calculation would output as float with decimals. However, I wonder if I may still use int for user input so that I can ensure the inputs are integers.
Extra question: Would it be possible to convert a float presented in the form of "#.##" to "# #/#"? More like how we do mathematics IRL.
You can use implicit conversion to double:
answer = (b-d)/(a-c*1.0);
Or explicit cast:
answer = (b-d)/(a-(float)c);
Bonuses:
for the fraction part: Converting decimal to fraction c++
Why does integer division result in an integer?
You can use int for user input, but to precisely calculate anything that contains a division operator /, you'll need to cast to floating point types.
It's usually considered a good practice in C++ to use static_cast for that (although you still may use c-style (float) syntax).
For example:
answer = static_cast<float>(b - d) / (a - c);
Here, you convert (b - d) to float and then divide it by integer, which results in a float.
Note that the following wouldn't work correctly:
answer = static_cast<float>((b - d) / (a - c));
The reason is that you first divide an int by another int and then convert the resulting int to a float.
P. S. float is really inaccurate, so I would advise to use double instead of float in all cases except where you want to write faster code that does not depend on mathematical accuracy (even though I'm not sure it would be faster on modern processors) or maintain compatibility with an existing library that uses float for some of its functions.

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

Rounding from math.h incorrect

I'm using the tasks on code abbey to work my way through C++.
I'm trying to use the rounding function by importing math.h and it works for every value that I'm trying to input apart from one pair
when I divide 4991264 by 4 and round it, it outputs the answer as 1.24782e+06
#include <iostream>
#include <math.h>
using namespace std;
int getTotal(){
int total;
cin >> total;
return total;
}
void doMath(int total){
int count;
double holder;
double holder2;
double solution;
solution = 0;
count = 0;
while (count != total){
cout << "enter a number ";
cin >> holder;
cout << "enter a number ";
cin >> holder2;
solution = (holder / holder2);
cout << round(solution) << "\n";
++count;
}
}
int main(){
int total = getTotal();
doMath(total);
return 0;
}
http://ideone.com/f40E1s is the code and the inputs.
Thanks,
A floating point variable keeps a value of a given type (in memory).
This value "rests" there with its own precision, in binary format.
When this value has to be shown or output in someway, typically is converted to decimal format. This conversion can have loss of precision sometimes.
Anyway, when you are doing precise arithmetica operations, as in your example, the conversion to decimal is not, in general, an issue.
What it has to be understood here is that "printing" a value is not the same that "showing the exact value held in memory".
The object cout has predefined ways to show the values you are computing.
The exact value has not changed, it's not, in this case, a problem of bad computing.
Indeed, it's only a matter of how to show this value on screen.
The format used to print the value is: in exponential notation with "only" 6 decimal digits precision.
You need to increase the precision of values when printed, and to avoid exponential notation.
Take a look to this website: Output formatting in C++
Thus, for example, the following code do the job (for a precision of 8 decimal digits):
cout << setiosflags(ios::fixed) << setprecision(8) << round(solution) << "\n";
In general, you have to investigate and practice more about this formatting options.

This program should give the AND of the following numbers. What does this mean?

For an assignment in my C++ programming class, I was given the following code. The assignment simply says "This program should give the AND of the following numbers" Was wondering if could get clarification on the meaning. I have an idea but I think I still need a bit of advice. The code was provided jumbled on purpose which I had to clear up. Here is is cleaned up:
// Question2
// This program should give the AND of the inputted numbers.
#include <iostream>
//**Needs namespace statement to directly access cin and cout without using std::
using namespace std;
//**Divided up statements that are running together for better readability
//**Used more spacing in between characters and lines to further increase readability
////void main()
//**Main function should include int as datatype; main is not typically defined as a void function
int main()
{
int i;
int k;
//**Changed spacing to properly enclose entire string
cout << "Enter 0 (false) or 1 (true) for the first value: " << endl;
cin >> i;
cout<< "Enter 0 (false) or 1 (true) for the second value: " << endl;
cin >> k;
//**Spaced out characters and separated couts by lines
//**to help with readability
cout << "AND" << endl;
cout << "k\t| 0\t| 1" << endl;
cout << "---\t| ---\t| ---" << endl;
cout << "0\t| 0\t| 0" << endl;
cout << "1\t| 0\t| 1" << endl;
if(i==1&k==1)
cout <<"Result is TRUE" << endl;
else cout << "Result is FALSE" <<endl;
//**Main function typically includes return statement of 0 to end program execution
return 0;
}
Every number has a binary representation. They're asking for the logical and of the bits. Look up the & operator.
'&' is a bitwise and, which means it takes the binary representation of two numbers and compares each bit in the first number against the bit in the same position on the second. If both are 1, the resultant bit in the same position in the output number is 1, otherwise the bit is zero. if (i&k) would have the same result (assuming the input was always 0 or 1), but anyway your if statement compares whether the first bit is 0 or 1, and if both are 1 returns one.
the AND gate(output) will be true only if both inputs are true(1)
true if i==1 && k==1
false if i==0 && k==0,i==1 && k==0,i==0 && k==1.