大家好我有一个1到1000个数字的数组
int[] Numbers={1,2,3,4,5,6............1000};
float CalculatedBy=3.5;
我希望通过CalculatedBy值(上面的浮点变量)将商和剩余值输入数组
我的代码:
首先,我将此数组拆分为char数组
Char[] splitNumbers=Numbers.split(",");
foreach( int charNumber in splitNumbers)
{
if(charNumber % CalculatedBy==0 )
{
//i know i am totally going to wrong way So what will i do ?
}
}
我的主要条件是:
我想在控制台窗口中使用此格式编写商数和剩余值
价值1: 结果是:Q为1,R为1
值2: 结果是:Q为1,R为1
我不想显示剩余的值是0。
答案 0 :(得分:1)
您可以使用以下代码:
int[] Numbers = { 1, 2, 3, 4, 5, 6, 7, 8 };
float CalculatedBy = 3.5F;
foreach (int number in Numbers)
{
if (number % CalculatedBy != 0)
{
int quotient = (int) Math.Floor(number / CalculatedBy);
float remainder = number - quotient * CalculatedBy;
Console.WriteLine("Value {0}: Result is : Q is {1} and R is {2}", number, quotient, remainder);
}
}
答案 1 :(得分:1)
您无需转换为char数组,
int[] Numbers = { 1, 2, 3, 4, 5, 6, 7, 8 };
float CalculatedBy = 3.5F;
foreach (int n in Numbers)
{
if (n % CalculatedBy != 0)
{
int q = (int) Math.Floor(n/ CalculatedBy);
float r = n- q * CalculatedBy;
Console.WriteLine("Value {0}: Result is : Q is {1} and R is {2}",n,q,r);
}
}
答案 2 :(得分:0)
当使用整数而不是浮点数时,另一种方法是使用Math.DivRem方法。
int[] Numbers = { 1, 2, 3, 4, 5, 6, 7, 8 };
int CalculatedBy = 3;
foreach (int number in Numbers)
{
if (number % CalculatedBy != 0)
{
int remainder;
int quotient = Math.DivRem(number, CalculatedBy, out remainder);
Console.WriteLine("Value {0}: Result is : Q is {1} and R is {2}", number, quotient, remainder);
}
}