Delphi 2010 for loop count

徘徊边缘 提交于 2019-12-11 04:34:49

问题


I have a problem with a For Loop. I need it to count a random amount of shopping sprees and amounts but display them in order like below. It also needs to take the amount of sprees and display it before.

Currently it displays total sprees as 0 and only displays 20 sprees which is not random.

You have won a total of 3 shopping sprees

On spree #1 you may spend R100

On spree #2 you may spend R341

On spree #3 you may spend R451

TotalCost := 0;

Sum := 0;

ListHead := 'Max per spree is R500.00 Max number of sprees 20';
lstNumber.Items.Add(ListHead);

  SpreeWon := 'You have won  ' + inttostr(Sum) + ' shopping sprees';
  lstNumber.Items.Add(SpreeWon);

for Count := 0 to 20 do
begin
    Sum := Random(Count);
    Prize := Random(500) + 1;
    ListItems := 'On spree # ' + inttostr(Sum) + ' you may spend R' + inttostr(Prize);
    lstNumber.Items.Add(ListItems);
    TotalCost := TotalCost + Prize;
end;
begin
    Cost := 'Total prize value : R' + inttostr(TotalCost);
    lstNumber.Items.Add(Cost);
end;

回答1:


Your code is not doing what your requirement asks for. You are displaying 20 sprees because you hard-coded it to generate 20 sprees, not a random number of sprees.

Try something more like this instead:

ListHead := 'Max per spree is R500.00 Max number of sprees 20';
lstNumber.Items.Add(ListHead);

Count := Random(20) + 1;
TotalCost := 0;

SpreeWon := 'You have won  ' + IntToStr(Count) + ' shopping sprees';
lstNumber.Items.Add(SpreeWon);

for I := 1 to Count do
begin
  Prize := Random(500) + 1;
  TotalCost := TotalCost + Prize;
  ListItems := 'On spree # ' + IntToStr(I) + ' you may spend R' + IntToStr(Prize);
  lstNumber.Items.Add(ListItems);
end;

Cost := 'Total prize value : R' + IntToStr(TotalCost);
lstNumber.Items.Add(Cost);


来源:https://stackoverflow.com/questions/12485256/delphi-2010-for-loop-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!