[英]How to? - Lottery Simulation (C)
我編寫了一個 C 程序,該程序將模擬用戶輸入的 X 年數的過程中的彩票抽獎,一旦輸入了年數,它將模擬每周一次的彩票抽獎多年。 程序還需要打印出預先輸入的數字(已經在代碼中)是否匹配,並打印出數字匹配的次數,例如
這是我到目前為止的代碼,一切都編譯並運行良好:
#include <stdio.h>
int main(int argc, char const *argv[])
{
//Welcome the User to the Program
puts("============================");
puts(" WELCOME TO ");
puts("============================");
puts(" PROJECT : JACKPOT DREAMS ");
puts("============================");
//Rogers 6 Original Numbers
int nums[6] = { 5, 11, 15, 33, 42, 43 };
//Ask how many years to simulate
int years = 0;
printf("How many years would you like to sleep for? :\n");
scanf("%d", &years);
printf("Ok. I will now play the lottery %d year(s)\n",years);
printf("Sleep Tight :)....\n");
//Generate Random Numbers
int ctr;
int randnums[6];
srand(time(NULL));
while (years-- > 0) {
for( ctr = 0; ctr < 6; ctr++ ) randnums[ctr] = (rand() % 50);
//Check Numbers with Rogerns numbers
int win = 1;
for( ctr = 0; ctr < 6; ctr++ )
{
if(randnums[ctr] != nums[ctr])
{
win = 0;
break; // if there's a mismatch we don't need to continue
}
}
return 0;
}
}
有誰知道我會怎么做?
首先,您似乎在循環第一年之后return
。 您應該將return
語句移到大括號外。 其次,正如一些評論所提到的,您應該更仔細地編寫塊,並進行正確的縮進。
下面我重寫了你的程序,如果某些數字與給定的年份匹配,則打印出來。 如果所有數字都匹配,“贏家!” 也印刷。 為此,我添加了一些變量和print
語句。
希望這可以幫助。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int
main(int argc, char const *argv[])
{
//Welcome the User to the Program
puts("============================");
puts(" WELCOME TO ");
puts("============================");
puts(" PROJECT : JACKPOT DREAMS ");
puts("============================");
//Rogers 6 Original Numbers
int nums[6] = { 5, 11, 15, 33, 42, 43 };
//Ask how many years to simulate
int years = 0;
printf("How many years would you like to sleep for? :\n");
scanf("%d", &years);
printf("Ok. I will now play the lottery %d year(s)\n",years);
printf("Sleep Tight :)....\n");
//Generate Random Numbers
int numberOfWins = 0;
int ctr;
int randnums[6];
srand(time(NULL));
int currYear = 0;
while (years-- > 0)
{
currYear++;
for( ctr = 0; ctr < 6; ctr++ ) randnums[ctr] = (rand() % 50);
//Check Numbers with Rogerns numbers
int win = 1, matched = 0;
for( ctr = 0; ctr < 6; ctr++ )
{
if(randnums[ctr] != nums[ctr])
{
win = 0;
} else {
matched++;
}
}
numberOfWins += win;
//If any numbers matched or win, print it.
if (matched > 0) printf("In year: %d, %d number(s) matched\n", currYear, matched);
if (win) printf("Winner!\n");
}
printf("You won %d time(s)\n", numberOfWins);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.