0

大家好,我有一个包含 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 。

4

3 回答 3

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);
    }
}
于 2013-10-08T05:23:23.527 回答
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);
    }
}
于 2013-10-08T05:26:02.190 回答
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);
    }
}
于 2016-03-23T13:16:43.827 回答