Click here to Skip to main content
15,392,679 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
code not working properly. i used num1%num2. cases where rem =0, its printing again nd again 0. Please the code.

What I have tried:

<pre>#include<bits stdc++.h="">
using namespace std;
int main()
{
    int num1,num2;
    cout<<"put num1>num2 \n";
    cout<<"num1:\n ";
    cin>>num1;
    cout<<"num2: \n";
    cin>>num2;
    int num=num1%num2;
    if(num=0)
    {cout<<"rem is zero";}
    else
    {cout<<"rem non zero";}  
}
Posted
Updated 3-Feb-22 6:38am
Comments
Rick York 3-Feb-22 22:19pm
   
If you can, you should turn the warning level up because this mistake is caught automatically when it is set high enough. I use Visual Studio and always have the warning level at 4 and warnings are errors and it always catches this error.

You are assigning in If block instead of checking the equality. Correct If condition
if(num==0)
{
    cout<<"rem is zero";
}
   
Comments
CPallini 4-Feb-22 2:03am
   
5.
M Imran Ansari 4-Feb-22 10:11am
   
Cheers.
You are not testing num for 0 correctly.

You should do

if(num == 0)

not

if (num=0)

In your code you are assigning 0 to num because you are using a single equals sign which will be successful which the if statement evaluates to true therefore always printing rem is zero.

A safer way to write it is

if (0 == num)

because if you miss one of the equals signs the compiler will complain you are trying to assign a value to a literal.
   
Comments
CPallini 4-Feb-22 2:03am
   
5.
Tony Hill 4-Feb-22 3:04am
   
Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900