2014-02-10 55 views
0

嗨我創建了這段代碼,但現在我卡住了。 如何添加除了可被5整除的N1和N2之間的所有數字? 並顯示結果?隨機數加法問題

問題:我的if聲明如果y可以被5整除不添加,只添加不能被5整除的數字。我不知道該怎麼做。

新代碼如何呢?

     Console.Write("Enter N1 : "); 
         int N1 = int.Parse(Console.ReadLine()); 
         Console.Write("Enter N2: "); 
         int N2 = int.Parse(Console.ReadLine()); 
         int counter = 1; 
         while() 
         { 
          Console.Write(""); 
          counter++; 
         } 
+6

什麼異常?在哪一行?我們不喜歡猜測... – MarcinJuraszek

+0

@MarcinJuraszek我的if語句如果y可以被5整除不添加只能加上不能被5整除的數字我不知道該怎麼做。 – TheBoringGuy

+2

哦,所以它只是* my **除了**條件不工作*,不是*代碼拋出異常* ...您應該更加精確。 – MarcinJuraszek

回答

3

如何添加所有的N1和N2之間的數字,以下項目除外5整除?

如果想法是在N1和N2之間添加每個數字,爲​​什麼使用隨機?你的問題很混亂。

Console.WriteLine("N1: "); 
int N1 = Convert.ToInt32(Console.ReadLine()); 
Console.WriteLine("N2: "); 
int N2 = Convert.ToInt32(Console.ReadLine()); 

int sum = 0; 
for (int X = N1; X <= N2; X++) 
{ 
    if (X % 5 != 0) 
    { 
     sum += X; 
    } 
} 
Console.WriteLine("Sum: {0}", sum.ToString()); 
Console.ReadLine(); 
+1

你應該檢查這個條件嗎? IF(N1> N2) – iJay

+0

@IJ迴路條件會爲我檢查。如果這是真的,'sum'將是默認的'0',因爲循環主體根本不會被執行。 – MarcinJuraszek

+2

因此,除了可以被5整除的數字之外,他會在30和20之間添加數字「0」? – iJay

0

循環將只運行五次。它如何添加範圍n1和n2中的所有數字?

使用此邏輯:

int sum=0; 
for(int i=N1;i<=N2;i++) 
{ 
    if (!(i%5 == 0)) 
     sum=sum+i; 

} 
console.writeline(sum); 
0

注意:使用的TryParse避免無效輸入異常,其餘的事情都是爲

這裏,如果用戶爲N1小,n2爲大於或反之亦然進入輸入,兩者的處理方式:

 Random rnd = new Random(); 
     Console.WriteLine("N1: "); 
     int N1 = 0; 
     int total = 0; 
     int.TryParse(Console.ReadLine(), out N1); 
     Console.WriteLine("N2: "); 
     int N2 = 0; 
     int.TryParse(Console.ReadLine(), out N2); 
     int x1 = 0, x2 = 0; 
     if (N1 < N2) 
     { 
      x1 = N1; 
      x2 = N2; 
     } 
     else 
     { 
      x1 = N2; 
      x2 = N1; 
     } 
      for (int X = x1; X <= x2; X++) 
      { 
       int y = rnd.Next(N1, N2); 
       if (y % 5 == 0) 
       { 
        Console.WriteLine(""); 
       } 
       else 
       { 
        total = total + y; 
        Console.WriteLine(""); 
       } 
      } 
     Console.ReadLine(); 
0

使用rnd.Next(N1, N2);

返回一個隨機整數,它是一個規定的範圍內。

試試這個,你不需要else條件。只是檢查它是否不能被5整除,並將其添加到totalSum中:

int totalSum = 0; 
for (int x = N1; x <= N2; x++) 
{ 
    int y = rnd.Next(N1, N2); 
    if (y % 5 != 0) 
    { 
     totalSum += y; 
    } 
}