+ 1
What is the difference between '%' and '&' in C program ?
8 ответов
+ 6
45 % 30 = 15
because modulo operator returns remainder of division.
45 & 30 = 12
because it's bitwise AND operation. In bitwise AND operation every bit of first operand is compared with corresponding bit of second operand. if both bits equal to 1 then only corresponding bit in resulting number will be set to 1 otherwise 0.
00101101 //8 bit binary representation of 45
00011110 //8 bit binary representation of 30
00001100 // result of 45 AND 30. this is binary equivalent of decimal 12. Note how a bit is set to 1 only when corresponding bits in both numbers are 1.
Please read on "Number systems" and "Bitwise operation" topics. It maybe bit hard to understand it from text but do a bit of research on internet. You can find good visual explanation on bitwise AND operation.
+ 4
both of them have more than one use.
& can be used as bitwise AND operator or address-off operator
% is used as modulo operator and also as format specifier in functions like scanf, printf
Please use proper tag in your question.
+ 4
Why have you written this line?:
days = days%30;
or this one:
days = days&30;
Number of days is already given you don't need to derive it. So, just remove that line.
For the number of month you have written :
month = days/30;
but in C when you divide an int by another int the result is always int. The fractional part is discarded.
For example if days = 45. then 45/30 should be 1.5 but since fractional part is discarded it'll result in 1 only.
To avoid this change data type of month variable to double or float (change format specifier in scanf accordingly) and change division formula to month = days/30.0; //note the division by 30.0 which is a double not int.
+ 1
#include<stdio.h>
main()
{
int month, days;
printf("Enter Days\n");
scanf("%d",&days);
month = days/30;
days = days%30;
printf("Months = %d days = %d",month, days);
}
+ 1
#include<stdio.h>
main()
{
int month, days;
printf("Enter Days\n");
scanf("%d",&days);
month = days/30;
days = days&30;
printf("Months = %d days = %d",month, days);
}
+ 1
Why..it's not working well...!!!
+ 1
I understand but..
Please copy both of that codes... and run once with giving the number of days 45... you'll see the difference...
'days%30'..shows that 1 month 15 days.
And 'days&30' shows that 1 month 12 days.
+ 1
In special cases bitwise & can be a much faster replacement for modulo %. The replacement works only if the modulus is a power of 2. Here is an example:
k % 8 //8 is 2*2*2=1000 in binary
k & 7 //7 is 8 - 1=0111 in binary
Both of the above expressions give the same result. Both only allow values 0 through 7.
This trick does not work for any non-binary modulus. And it does not work by using the same value as the modulus (k % 30 != k & 30).