Rounding Numbers - Ceil & Floor

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>
using namespace 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!
Last edited on
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.

There is a difference between "display 4" and "display a value that is 4".
See http://www.cplusplus.com/reference/ios/fixed/

Header <iomanip> contains more tools for "display X". See http://www.cplusplus.com/reference/iomanip/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

int main ()
{
  using std::cout; // like using namespace std, but only for std::cout

  const double multiplier = 1.5;
  int number = 3;

  const int foo    = number * multiplier;
  const double 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;
}
My mistake, I am familiar with double. multiplier should have been double ._.

Lots of links, lots of links, thanks, give me a few minutes to look through these.

Why do you use "const" behind some of the variables like foo and bar?

So basically if an integer variable is set as a decimal, it automatically rounds the number down?
Last edited on
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.
Topic archived. No new replies allowed.