0

一个书本练习提示我创建一个模拟抛硬币的程序。我的朋友说他在本机 GNU 编译器中运行了我的代码,并且它可以工作,但是当我尝试在 Visual Studio 2010 中运行它时收到以下错误:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int result;

int flip();

int main(void)
{
    srand(time(NULL));

    int heads = 0;
    int tails = 0;
    unsigned counter;

    for(counter = 1; counter <= 100; counter++)
    {
        result = flip();

        if(result == 1)
        {
            printf("Heads\n");
            heads++;
        }

        else
        {
            printf("Tails\n");
            tails++;
        }
    }

        printf("Heads: %d\tTails: %d\n", heads, tails);
}

int flip()
{
    result = 1 + rand() % 2;

    if (result == 1)
        return 1;

    if (result == 2)
        return 0;

    return NULL;
}

syntax error: ')' (line 10)

'counter': undeclared identifier (15, 23)

'heads': undeclared identifier (19, 23)

't': undeclared identifier (10, 10)

syntax error: missing ')' before 'type' (line 10)

syntax error: missing ';' before '{' (line 11)

syntax error: missing ';' before 'type' (9, 10, 10, 10)

感谢您的任何回复。

4

3 回答 3

0

这是一个修改后的代码,它在 eclipse 中运行良好:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int result;

int flip();

int main(void)
{
    srand(time(NULL));

    int heads = 0;
    int tails = 0;
    unsigned counter;

    for(counter = 1; counter <= 100; counter++)
    {
        result = flip();

        if(result == 1)
        {
            printf("Heads\n");
            heads++;
        }

        else
        {
            printf("Tails\n");
            tails++;
        }
    }

        printf("Heads: %d\tTails: %d\n", heads, tails);

        return 0;
}

int flip()
{
    result = 1 + rand() % 2;

    if (result == 1)
        return 1;

    if (result == 2)
        return 0;
}

错误:在 main 中,您忘记了“return 0”语句。在翻转函数中,您编写了不应该存在的“返回 NULL”。在 vs 中试试这个代码。

于 2013-06-27T05:56:38.130 回答
0
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void){
int heads = 0,tails = 0;
unsigned int counter = 1;
int result = 0;

srand(time(NULL));

for(counter = 1; counter <= 100; counter++){
    result = rand()%2;

    if(result == 1){         
        heads++;
    }
    else{
        tails++;
    }
}
printf("Heads: %d\tTails: %d\n", heads, tails);     
return 0;
}
于 2013-06-27T06:45:43.930 回答
0
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int result;

int flip();

int main(void){
    int heads = 0;
    int tails = 0;
    unsigned counter;

    srand(time(NULL));//Executable statement after the declaration

    for(counter = 1; counter <= 100; counter++){
        result = flip();

        if(result == 1){
            printf("Heads\n");
            heads++;
        } else {
            printf("Tails\n");
            tails++;
        }
    }

    printf("Heads: %d\tTails: %d\n", heads, tails);
    return 0;
}

int flip() {
    result = 1 + rand() % 2;

    return result == 1;
}
于 2013-06-27T09:05:20.120 回答