1

So basically I am trying to develop a simple application that uses a function to determine whether from 2 numbers input by a user, the second number is a multiple of the first.

#include<iostream>
using namespace std;
int multiple( int n1, int n2){
    if(n1%n2 ==0)return 1;
    else return 0;
}

int main(){
    int num1, num2;
    cout<<"Enter 2 numbers (-1 to exit): ";
    cin>>num1>>num2;
    while (num1 !=-1 && num2 != -1){
        if (multiple (num1, num2)==1)cout<<num2<<" is a multiple of "<<num1<<endl<<endl;
        else cout<<num2<<" is not a multiple of "<<num1<<endl<<endl;
        cout<<"Enter 2 numbers (-1 to exit): ";
        cin>>num1>>num2;
    }
    return 0;
}

Now when I try it with normal integers it works fine,but why is it that when I input the second number as a decimal, it enters an infinite loop? Specifically this is the statement it keeps giving:

"Enter 2 numbers (-1 to exit): 1 is a multiple of 0"

The debugger shows that num1 becomes 0 for some weird reason. I know I can overcome this by using an if statement, but for my own curiosity can anybody out there explain why this happens? I can provide you with any other thing you require, and I am using xCode if that is of any relevance.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • What do you think `cin >> num1 >> num2` does when you type something that isn't an integer? What does it put in the variables? – Barmar Apr 10 '14 at 20:27
  • 1
    The dot prevents reading the next integer. Look at [this](http://stackoverflow.com/questions/1283302/user-input-of-integers-error-handling) question and answers, it may help in your case as well. – Gassa Apr 10 '14 at 20:27
  • possible duplicate of [C++, getting a infinite loop](http://stackoverflow.com/questions/20002137/c-getting-a-infinite-loop) – Barmar Apr 10 '14 at 20:28
  • wouldn't it round it down, so for instance if I input 2.5, wont it store it as 2? – user3311681 Apr 10 '14 at 20:29
  • @user3311681: No. Input parsing and assigning variables to each other are two different things. It would be infeasible for a stream to always get it right if it were allowed to just guess at the type you meant. – Lightness Races in Orbit Apr 10 '14 at 20:29
  • By the way, if you were referring to my layout of code, how would you suggest I improve it? – user3311681 Apr 10 '14 at 20:33
  • By making it consistent and logical? – Lightness Races in Orbit Apr 10 '14 at 20:37

2 Answers2

1

You place both variables on a single cin.

It should look like this: cin >> num1; cin >> num2;

  • 2
    That will have absolutely no change in behavior. Their problem is trying to pass a decimal (`float`) into an `int`. – Cory Kramer Apr 10 '14 at 20:44
0

If by a "decimal number" you mean a non-integer, you can't put such in an int variable.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101