split an integer number into c++

Asked

Viewed 130 times

2

I made the following program below that guess the age of the person and the number that she thought, but the final result generates a number of 4 digits according to the calculations below suppose I have thought of the number 12:

Multiply by 2: 12*2=24

add 5: 24+5=29

Multiply by 50: 29*50=1450

std::cout<<"Digite o rsultado: 1450";
std::cin>>result=1450;

int var1(2017-250);
int var2(1450+1767);

std::cout<<"\n\tDigite seu ano de nascimento: ";
std::cin>>anonasc;

int var3(3217-1994);

The result contained in var3 would be 1223 where 12 would be the number I had thought and 23 my age, however it has some way of separating this result so that it shows separately the number thought and the age of the person?

I know if I do:

var3=1223/100;

he returns me

var3=12

but for me to get number 23 like I do?

2 answers

2

I don’t program in C++ but for you to recover 23 do the following:

int number = 1223;
int digit = number % 50;

See working on ideone

I don’t know if this is the best solution, maybe someone with experience can better answer the question.

  • worked here but wanted to understand why number%50?

  • number % 50 is the same as 1223 % 50

  • I know that I understood but why 50 and not any other number?

  • That’s a question I can’t answer, but you can open a question, and someone with experience in C++ answer you correctly.

2


The right thing to do var3 % 100 to catch the 23

We must not forget that the % (module) gives the rest of the division and so picks up what could not be divided.

Example:

1223 / 100 = 12

If we do 12 * 100 we have 1200, then what was left and couldn’t share was 1223 - 1200 = 23

Let us see the same principle of division and rest analyzing a simple case of 5 to be divided by 2:

inserir a descrição da imagem aqui

Here we see that:

  • 5 / 2 = 2
  • 5 % 2 = 1 which is the remaining value.

Note that the entire division was considered.

Online example of getting both parts of the number

Completion

Whenever you want to divide a number into two parts, you have to take the division and the rest of the division by the multiple of 10 what matters (10, 100, 1000, etc...)

  • Legal I did the program I used the first tip of the answer above and it worked now reissued and it was blzera https://pastebin.com/d6bmeCez

Browser other questions tagged

You are not signed in. Login or sign up in order to post.