2013-04-05 49 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++; 
    } 
}