So, hi guys, newbie programmer here, I've been working on a program that produces numbers with large decimals, but I don't want the end result to have any decimals at all.
For example,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <cmath>
usingnamespace std
int number = 3;
int multiplier = 1.5;
int main ()
{
number = number*multiplier;
//Rounding down numbers function goes here.
cout<<number<<endl;
//If this is done right, number should be displayed as 4.
system("pause")
}
The first question is, can this be done, or do I have to change all the int's to doubles?
Also, I was wondering whether someone could help me with the ceil and floor functions, as I've never used <stdio.f> and I don't know how to type the same code in <iostream>.
If there is anything missing, please do post below and I will gladly fill in for you. Thanks in advance!
Your line 6 does the same as writing int multiplier = 1;. You have to use a floating point datatype (double), If you want to store a floating point value.
It is not recommended to use line 3. There is a good reason, why the standard library is in a namespace.
It is not recommended to use global variable, except when they are absolutely necessary. That is almost never.
#include <iostream>
int main ()
{
using std::cout; // like using namespace std, but only for std::cout
constdouble multiplier = 1.5;
int number = 3;
constint foo = number * multiplier;
constdouble bar = number * multiplier;
number *= multiplier; // a*=b does same as a=a*b
cout << foo << '\n';
cout << bar << '\n';
cout << number << '\n';
cout << std::fixed << bar << '\n';
cout.precision( 0 );
cout << bar << '\n';
return 0;
}
Integral types cannot store fractional values. Thus, the fraction is discarded when a floating point value is converted to integral type. That is similar to rounding down.
I do use const to express that those variables will not be modified later in the program. The compiler ensures that I won't accidentally break my intent. It is a good habit to use const (where appropriate). Latest C++ standard has also keyword constexpr. More fun.