Check if a number is integer, if not, make the user type again

Asked

Viewed 94 times

-2

The idea is to make a program that asks the user a number, check if this number is real positive otherwise, request to type again another number, this process can repeat countless times...


            cout<<"Digite um número: "<<endl;
            cin>>number;

            if(number % 2 == 0 ){
                cout<<"O número é real positivo"<<endl;
            } else {
                cout<<"O número não é real positivo, por favor, digite novamente: "<<endl;
            }


            system("pause");
            return 0;```
  • Hello, there are some ways to solve your problem, the most appropriate one seems to me to be that of Junior Nascimento’s answer, but as this seems to be a challenge for beginners, I imagine it would be worthwhile to see how other repeating structures work and to try to solve the same problem with them too, doing so can make you more prepared for future challenges and will surely add knowledge. I will leave a link with a good article on the subject if you are interested: Devmedia About repetition structures in c .

2 answers

1

You can do it this way:

std::cout << "Digite um número: ";
do{
    std::cin >> number;
    if(number%2 == 0){ 
        std::cout << "O número é real positivo" << std::endl
    }else{
        std::cout << "O número não é real positivo, por favor, digite novamente: ";
while(number%2 == 0);
  • 1

    while(number%2 == 0)? Would not be while(number>0)? I know that the number % 2 == 0 I was already on the question, but I don’t think it was right.

  • I didn’t want to change anything he’d ever done. I spent a good few minutes wondering if I should even put the while so or else send an article with all the repeating structures.

0

The inserted number may not be integer, like 0.2. So it is preferable to use "doubles" and not "ints". So it would look like:

#include<bits/stdc++.h>    //uma grande biblioteca de funções que inclui tudo o que é necessário
using namespace std;

double number;

int main (){
number=-1;
  while(number<=0){
    cout << "Digite um número: ";
    cin >> number >> endl;
    if(number>0){
      cout<<"O número é real positivo"<<endl;
    }else{
      cout<<"O número não é real positivo, por favor, insira novamente
    }
  }
  return 0;
}

Browser other questions tagged

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