开发者

C# How to determine if a number is a multiple of another?

Without using string manipulation (checking for an occurrence of the . or , character) by 开发者_如何学Gocasting the product of an int calculation to string.

and

without using try / catch scenarios relying on errors from data types.

How do you specifically check using C# if a number is a multiple of another?

For example 6 is a multiple of 3, but 7 is not.


Try

public bool IsDivisible(int x, int n)
{
   return (x % n) == 0;
}

The modulus operator % returns the remainder after dividing x by n which will always be 0 if x is divisible by n.

For more information, see the % operator on MSDN.


bool isMultiple = a % b == 0;

This will be true if a is a multiple of b


Use the modulus (%) operator:

6 % 3 == 0
7 % 3 == 1


I don't get that part about the string stuff, but why don't you use the modulo operator (%) to check if a number is dividable by another? If a number is dividable by another, the other is automatically a multiple of that number.

It goes like that:

   int a = 10; int b = 5;

   // is a a multiple of b 
   if ( a % b == 0 )  ....


I tried to solve this problem using the modulus operator (%), but it did not work. What worked for me was (12 is an example, it can be any number, i is an integer number):

double v1 = i / 12.0;
int v2 = i / 12;
double dif = v1 - v2;
bool boolDif = false;
if (dif==0.0)
{
   boolDif = true;
   //more code here
}


Here is what we do in the case of having doubles to compare. E.g. value == 1.2d and baseValue == 0.1d shall give true and 1.2d and 0.5d shall give false:

    public static bool IsMultipleOf(double value, double baseValue)
    {
        var d = value / baseValue;
        return Math.Abs(d - Math.Round(d, MidpointRounding.AwayFromZero)) <= 1E-05;
    }


followings programs will execute,"one number is multiple of another" in

#include<stdio.h>
int main
{
int a,b;
printf("enter any two number\n");
scanf("%d%d",&a,&b);
if (a%b==0)
printf("this is  multiple number");
else if (b%a==0);
printf("this is multiple number");
else
printf("this is not multiple number");
return 0;
}


there are some syntax errors to your program heres a working code;

#include<stdio.h>
int main()
{
int a,b;
printf("enter any two number\n");
scanf("%d%d",&a,&b);
if (a%b==0){
printf("this is  multiple number");
}
else if (b%a==0){
printf("this is multiple number");
}
else{
printf("this is not multiple number");
return 0;
}

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜