彩票模拟编译问题

时间:2019-03-21 00:38:46

标签: c

我已经开始使用C编程编写彩票模拟程序,但是当我编译该程序时,却出现了我不理解的编译错误。

#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? :");
        scanf("%d", &years);
        printf("Ok. I will now play the lottery %d year(s)");
        printf("Sleep Tight :)....");
    //Generate Random Numbers
        int ctr;
        int randnums[6];
        srand(time(NULL));
        for( ctr = 0; ctr < 6; ctr++ ) randnums[ctr] = (rand() % 50);

    //Check Numbers with Rogerns numbers
        int win;
        for( ctr = 0; ctr < 6; ctr++ ) (randnums[ctr] == nums[ctr]) ? win = 1 : win = 0;




    return 0;
}

这是我得到的编译错误:

LotteryNumbers.c:29:79: error: expression is not assignable
  ...= 0; ctr < 6; ctr++ ) (randnums[ctr] == nums[ctr]) ? win = 1 : win = 0;
                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^
4 warnings and 1 error generated.

2 个答案:

答案 0 :(得分:1)

问题是因为使用ternary operator时的语法是:

<condition> ? <true-case-code> : <false-case-code>; 

因此,您的情况:

for( ctr = 0; ctr < 6; ctr++ ) win = (randnums[ctr] == nums[ctr]) ? 1 : 0;

但是,并非所有数字都匹配,它只是将win设置为检查当前数字的结果。要检查所有数字是否匹配,可以尝试:

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
    }
}

答案 1 :(得分:0)

更改:

for( ctr = 0; ctr < 6; ctr++ ) (randnums[ctr] == nums[ctr]) ? win = 1 : win = 0;

收件人:

for( ctr = 0; ctr < 6; ctr++ ) win = (randnums[ctr] == nums[ctr]) ? 1 : 0;