用C编程
时间:2020-02-23 14:32:05 来源:igfitidea点击:
我们现在就开始用C编写基本程序。
您需要在系统中安装和配置必需的软件。
请参阅Hello World的文章,并确保您能够编译和运行该程序。
了解基本语法
语法基本上是语言中的语法或者单词排列。
在他看来,并不是每一个细节都能使事情变得简单,但是涵盖了必要的事情。
看下面给出的程序
#include <stdio.h>
void main()
{
printf("Hello World");
}
- #include <stdio.h>
简而言之,请将上一行理解为对编译器的说明"嘿,C编译器,在编译源代码时包含(或者引用)此stdio.h文件,以便您可以理解所用单词和函数的含义,例如printf(),scanf()等。
"这是因为stdio.h文件与编译器一起提供,该文件具有其中定义的各种常用功能的含义(定义)。
- void main()
它是程序执行的起点。如果没有main(),则没有输出。
void是一种返回类型,稍后您将通过函数的概念了解它。
大括号(大括号“{}”)定义了作用域,也就是说,功能代码应该在这些大括号中才能工作。
用C编程
现在,我们将从用C编写一些基本程序开始,了解语法并在顺序流中工作。
- 加2个数字
#include <stdio.h>
int main()
{
//Declaring Identifiers(variables)
int num_a;
int num_b;
int num_result;
//Take input from user when program is running
printf("Enter a value of num_a: ");
scanf("%d",&num_a);
printf("Enter a value of num_b: ");
scanf("%d",&num_b);
//Adding numbers and assigning to identifier
num_result = num_a + num_b;
//Printing result as Output
printf("Sum is %d", num_result);
}
- 交换2个数字
它使用第三个变量交换2个变量中的值。
#include
int main()
{
int num_a;
int num_b;
int num_temp; //Temporary variable used for swapping.
printf("Enter a value of num_a: ");
scanf("%d",&num_a);
printf("Enter a value of num_b: ");
scanf("%d",&num_b);
//Assigning value of num_a in num_temp variable.
num_temp = num_a; //num_a and num_temp has same value
//Assigning value of num_b into num_a
num_a = num_b;
//Assigning value of num_temp which has original value of num_a to num_b
num_b = num_temp;
//Printing Output
printf("Value of num_a: %d", num_a);
printf("\n"); //To print next output in next line
printf("Value of num_b: %d", num_b);
}

