tutorial 3 - writing hello world!
使用linux系统运行c,
安装gcc,为compiler,使用vim等工具写好hello world程序,命名hello.c
#include <stdio.h>
int main(){ //int means the returned data type
printf("hello world!\n"); // \n means a new line
return 0; //the program worked as expected
}
之后在terminal中输入:gcc hello.c,之后会自动生成a.out文件,然后输入 ./a.out 运行
tutorial 10 - print variable using printf();
#include <stdio.h>
int main(){
int x = 10;
int y = x/2;
printf("the magic number is: %i\n",y); //"", is a format string, and %i inside means it's an integer, \n is new line, y is the variable you want to print
printf("the magic number is: %i\nThe value x is: %i\n",y,x);//this will work too, first string,y and x are arguments
return 0;
}//the first output is 5;
tutorial 12 - taking user input and float or double datatype
#include <stdio.h>
int main(){
int radius;
printf("Please enter a radius");
scanf("%i",&radius); //scanf will ask user to input a value, the & sign in front of the radius means store the input value to this address; address-of
float area = 3.14 * radius * radius; //float can store decimal numbers
printf("the area is : %f\n",area);//because area is a float type, the format string must use %f
return 0;
}
tutorial 13 - type casting
#include <stdio.h>
int main(){
printf("enter the number of eggs for the day: ");
int eggs;
scanf("%i",&eggs);
double dozen = (double) eggs / 12; //type casting means egg now is a double type, other wise the output will always be an whole number, because eggs and 12 are both integer, even though dozen is double type.
printf("you have %f dozen eggs .\n",dozen);
return 0;
}
tutorial 14 - working with strings
#include <stdio.h>
int main(){
char name[31]; //for string array, we need one more character "\0" to indicate the array is finished
printf("Please enter your name: ");
scanf("%s",name)://for array, do not add & in front of the variable,
printf("Hello, %s",name);
return 0;
}
tutorial 30 - operators
tutorial 35 - assignment operators
int main(){
int pizzasToEat = 100;
pizzasToEat += 100; //200
pizzasToEat -=100; //100
pizzasToEat *=2; //200
pizzasToEat /=4; //50
pizzasToEat %=5; //0
return 0;
}
tutorial 36 - operator precedence
https://en.cppreference.com/w/c/language/operator_precedence
tutorial 40 - type cast operator
int main(){
int slices = 17;
int people = 2;
double halfThePizza = (double) slices / people;//double has a higher precedence then division
printf("%f\n",halfThePizza);
return 0;
}
参考内容: