2013-04-05 48 views
-1

我試圖做一個簡單的程序來顯示折扣取決於客戶購買的項目數。一組值範圍中的數組值不顯示

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace ConsoleApplication11 
{ 
    class Program 
    { 
     const int SIZE = 4; 
     static void Main(string[] args) 
     { 
      int itemsbought = 0; 
      double discountItem = 0; 
      int[] items = new int[SIZE] { 0, 10, 26, 61 }; 
      double[] discount = new double[SIZE] { 0.0, 0.05, 0.10, 0.15 }; 

      InputItems(ref itemsbought); 
      getDiscount(items, discount, ref itemsbought, ref discountItem); 

      Console.WriteLine("Your discount is {0}", discountItem); 

     } 

     private static void getDiscount(int[] items, double[] discount, ref int itemsbought, ref double discountItem) 
     { 
      int idx = 0; 
      for (idx = 1; idx >= items.Length; idx++) 
      { 
       while (itemsbought >= items[idx]) 
       { 
        discountItem = discount[idx]; 
        idx++; 
       } 
      } 
     } 
     private static void InputItems(ref int itemsbought) 
     { 
      Console.WriteLine("Enter the amount of items you bought"); 
      while (!int.TryParse(Console.ReadLine(), out itemsbought)) 
       Console.WriteLine("Error, whole numbers only"); 
     } 
    } 
} 

不知怎的,我知道這樣做的邏輯是非常糟糕,但我不知道。主題之一當然是顯示與輸入對齊的折扣。無論輸入什麼值,它都會顯示「折扣爲0」。

回答

1

您的for循環都是錯誤的。首先,它沒有執行,因爲你的條件是idx >= items.Length;。它應該是相反的:idx < items.Length;。其次,我不知道爲什麼你在初始化器中設置idx1 ...

inner while循環也可能不會做你想要的,但我甚至不確定它是什麼你希望它首先做到這一點。

0

您需要修復環路狀態檢查部分,它使用的故障邏輯idx >= items.Length;應該是idx < items.Length;

c#中的數組有零基索引,所以它必須以idx = 0開頭。

for (idx = 0; idx < items.Length; idx++) 
{ 
    while (itemsbought >= items[idx]) 
    { 
     discountItem = discount[idx]; 
     idx++; 
    } 
}