第一个程序Hello world
很多程序员们, 第一行代码可能就是Hello world了吧!
C语言必写框架_最简单的程序!
int main()
{
return 0;
}
main 是主函数, 程序的开始与结束都从他开始。
return 0; return 结束函数(可以先忽略) 因为程序的开始和结束都要从main函数开始, 0告诉操作系统, 程序正常结束。
; 是结束符, 有结束符的是语句, 没有结束符的是表达式, 所以每一个语句后面一定一定不要漏掉结束符哦!
特别提示: 一个C程序是由若干个头文件函数组成的, 写完一句代码要按一下保存(ctrl + s)。
实现Hello world的两种方式
/*
* 编写时间: 2018/7/21
* 编写作者: 流光飞霞
* 程序功能: 打印Hello world
* 版本号 : V1.00
**/
# include <stdio.h> /* 预处理命令, 引用了标准输入输出的函数库 */
int main()
{
printf("%s\n", "Hello world!"); /*
输出部分
**/
printf("Hello world!\n"); //输出部分
return 0;
}
代码拆解
# include <stdio.h> 是程序的头文件(预处理命令), 使用了标准的输入输出(i / o)库。
include 的英文意思是包含。
调用函数库有一下两种写法
# include <stdio.h>
# include “stdio.h”
# include <stdio.h> 一般是系统的。
# include “stdio.h” 一般是自己写的。
int main() 是主函数程序如入口与出口, 当然也可以写成 main(), 不过为了更规范的代码, 最好写成int main()。
直接写成 main() 等价于 int main()。
printf(); 语句是<stdio.h>函数库里面的一个函数(格式化输出函数), 编译的时候, 会检查有没有这个函数, printf是函数名, ()里面的是形式参数(形参), 形参和函数后面会讲到, 可以先忽略, 先知道怎么写出一个Hello world程序。
这是什么字符啊?
%s 是格式字符代表以字符形式输出。 (后面会详细讲)
\n 是转义字符代表的是回车换行。 (后面会详细讲)
也可以说: 新的一行
注意: 转义字符和格式字符都要放在字符串内部!
/**/ 是块注释, 用于多行注释。
// 是行注释, 用于单行的注释。
为什么我的程序会闪退呢?
因为你没有让程序等待你的输入, 或者让程序暂停。
如何操作?
第一种解决方法: 让程序等待输入一个字符
/*
* 编写时间: 2018/7/21
* 编写作者: 流光飞霞
* 程序功能: 让程序等待输入一个字符
* 版本号 : V1.00
**/
# include <stdio.h>
int main()
{
printf("Hello world");
getchar(); /* 等待输入一个字符 */
return 0;
}
第二种解决方法: 让程序暂停
/*
* 编写时间: 2018/7/21
* 编写作者: 流光飞霞
* 程序功能: 调用命令pause来使程序暂停
* 版本号 : V1.00
**/
# include <stdio.h>
# include <stdlib.h> // 二选一
# include <windows.h> // 二选一, 不过在Linux系统下没有这个函数库
int main()
{
printf("Hello world");
system("pause"); // 调用命令pause 也就是暂停
return 0;
}
有两种方法你喜欢哪一种呢?
与其他语言对比
Python
print "Hello world"
input()
JAVA
public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
C#
using System;
namespace HelloWorldApplication
{
class Hello
{
static void Main(string[] args)
{
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
HTML
<!DOCTYPE html>
<html>
<body>
<h1>第一个程序Hello world</h1>
<p>Hello world</p>
</body>
</html>
课后作业
- 编写一个 China is very good 程序。
- 在本文下方评论(指正作者的错误 与 随笔意见), 让作者写出更好的文章。
- 找出以下程序的错误
include <stdio.w]
mani()
{
printf(“C is fun\n”)
return 0;
}