intmain gets SyntaxError in Google Collaboration

Asked 1 years ago, Updated 1 years ago, 390 views

Programming a 2D random walk

I entered it on Google Colab, but the following error appears.
Please tell me how to fix it.

error messages:

File"<ipython-input-3-95051bfc0730>", line 8
    int main()
           ^
SyntaxError: invalid syntax

source code:

#include<stdio.h>
# include <stdlib.h>
# include <math.h>
#define n100
#define m10000
# define seed 7892
int main() ← There was an error here.
{
    inti,j;
    double x, y, r, rn, sum, average;
    FILE* output;
    output=fopen("output.data", "w");
    sum = 0.0;
    sland(seed);
    for(j=1;j<m;j++){
        x = y = 0.0;
        for(i=1;i<n;i++){
            rn = land()/(RAND_MAX+1.0);
            if(rn<0.25)x = x-1.0;
            else if(rn>=0.25&rn<0.5)x=x+1.0;
            else if(rn>=0.5&rn<0.75)y=y-1.0;
            else = y + 1.0;
        }
        r = sqrt(x*x+y*y);
        sum+=r;
    }
    average=sum/m;
    printf("%f\n", average);
    fclose(output);
    return 0;

c google-colaboratory

2022-09-30 22:01

1 Answers

As in this article, it seems that non-Python source programs have to include a designation to save to a file at the beginning.
Can you run programs in C language in Google Collaboration?

Create an Edit Source Program

When you create a source program in your notebook in C language, you will need to start the code cell with a description like %%file hello.c.Other than describing the line, write the program normally.

In the case of the question program, it is a random walk, so you can insert the following line at the beginning.

%%file randomwalk.c

By the way, the source program of the question article is missing the last }.

A similar source program appears later in this article.
Random Walk Numerical Calculation Example (C language)

And it seems that you need to do the following to save the source program to storage.

However, once you have written the source program, remember to press the Run Cell button in the upper left corner of the code cell to store (write) the source program in the storage of the instance.

You will then compile and run the C language source program you saved.
Compile and Run Run

The above introduction was simple because it only shows Hello World!..., but the program in question uses sqrt() in math.h, so you need to specify a link to that library.
Don't forget to link your library

Add a new cell after the source program, type and run as follows, and you will see the results.

!gcc randomwalk.c-lm-orandomwalk & ./randomwalk


2022-09-30 22:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.