簡體   English   中英

如何獲取int數組中的元素數?

[英]How to get the number of elements in an int array?

在這種情況下,我想取數組中的元素數,但數組取決於用戶輸入

int first = int.Parse(Console.ReadLine());
int second = int.Parse(Console.ReadLine());
for (int i = first; i <= second; i++)
{
    if (i % 5 == 0)
    {
        int[] some =new int [i];
        int c =some.Length;
        Console.WriteLine(c);
    }
}

我嘗試了幾個選項,但輸出仍然是一個可以被 5 整除且沒有余數的數字列表。 怎么做才是對的?

例如: first = 15second = 50 預期輸出 = 8

8 個可被 5 整除的無余數 (15,20,25,30...50)

您可以循環遍歷數字並計算您找到的可被 5 整除的數量:

int first = int.Parse(Console.ReadLine());
int second = int.Parse(Console.ReadLine());
int cnt = 0;
for (int i = first; i <= second; i++) {
  if (i % 5 == 0) {
    cnt++;
  }
}

但是,您不必生成數字即可知道有多少。 您可以計算最后一個數字在哪里(因為這比第一個更容易),然后計算在此之前但在第一個之后有多少:

int first = int.Parse(Console.ReadLine());
int second = int.Parse(Console.ReadLine());
second -= second % 5;
int cnt = (second - first) / 5 + 1;

例如,對於輸入311您要計算數字510 表達式11 % 5給出1 ,所以second變成10 (最后一個數字)。 然后second - first7 ,用5做整數除法得到1 ,然后加1得到2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM