Division of integers

I want to convert an integer into two separate integers, thousands and hundreds

examples:

4796 = 4 and 796

12765 = 12 and 765



If I try using the following to get the thousands I get an error as the result is floating-point.


{
int thousands
int hundreds

thousands = 4796/1000
hundreds = 4796 - (thousands * 1000)
}



How can I get the result of the division as an integer?


If I try using the following to get the thousands I get an error as the result is floating-point.


Not that I can see.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

using std::cout;

int main()
{
  int thousands;
  int hundreds;

  thousands = 4796/1000;
  hundreds = 4796 - (thousands * 1000);

  cout << "thousands: " << thousands << '\n' << "hundreds: " << hundreds;
}


No floating-point in there. Works as expected.
Last edited on
It's also possible to use std::to_string() and stoi(), but I think the above solution is better.
Curious as to why one might want to avoid %, as in

@Repeater's code largely, just another approach

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

using std::cout;

int main()
{
  int thousands;
  int hundreds;

  thousands = 4796/1000;
  hundreds = 4796 % 1000;

  cout << "thousands: " << thousands << '\n' << "hundreds: " << hundreds;
}
Last edited on
Modular arithmetic is not typically taught in US education until College or University, sadly. The idea of a remainder is something that was taught and forgotten sometime around fourth grade.

Hence, beginning programmers are not really aware of the concept, let alone useful application.

@Cplusbug
What are the actual code and error message(s) you are seeing?
Topic archived. No new replies allowed.