Jul 22, 2019 at 3:27pm UTC
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?
Jul 23, 2019 at 9:19am UTC
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 Jul 23, 2019 at 9:50am UTC
Jul 23, 2019 at 9:27am UTC
It's also possible to use std::to_string() and stoi(), but I think the above solution is better.
Jul 23, 2019 at 11:28am UTC
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 Jul 23, 2019 at 11:29am UTC
Jul 23, 2019 at 7:26pm UTC
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?