B2002题解

· · 题解

注:本题为基础练习题目

代码:

#include <bits/stdc++.h>
using namespace std;
int main ()
{
  cout << "Hello,World!";
  return 0;
}

注解:

其中第一行 include 为引用头文件,常见的头文件有: bits/stdc++.h,iostream,cmath 等。不同的头文件拥有不同的函数。其中 bits/stdc++.h 是万能头文件,包含了几乎所有可以用到的普通头文件。

第二行引用了 std 这个命名空间。using namespace 表示引用命名空间。std 是最常用的命名空间,包含了输入输出流、STL 等。调用命名空间还有一种方式,就是在需要命名空间的语句前面加上 命名空间 :: 例如 std::cout<<"Hello,World!";。

第三行是定义了一个名称为 main 的函数,类型为 int。main 函数为主函数,代码中必须有 main 函数。执行程序时,会自动执行 main 函数。

第五行为输入输出流。输入为 cin>>,后面加入变量。变量可以用 int,double 等定义。输出为 cout<<,后面加入变量或常量。

第六行使用 return 跳出了函数,返回 return 后加的值。只有 return 0 才能正常结束程序。

输入输出还有别的方式:

#include <bits/stdc++.h>
using namespace std;
int main ()
{
  printf ("Hello,World!");
  return 0;
}
#include <bits/stdc++.h>
using namespace std;
int main ()
{
  putchar ('H');
  putchar ('e');
  putchar ('l');
  putchar ('l');
  putchar ('o');
  putchar (',');
  putchar ('W');
  putchar ('o');
  putchar ('r');
  putchar ('l');
  putchar ('d');
  putchar ('!');
  return 0;
}

printf 主要用于格式化输出,而 putchar 是快速输出方式。

cin,cout 优化:

尽管 cin,cout 十分常用,但是它的速度非常慢。可以用 ios 命名空间的一个函数来优化。

#include <bits/stdc++.h>
using namespace std;
int main ()
{
  ios :: sync_with_stdio (false);
  cout << "Hello,World!";
  return 0;
}

这个函数用于关闭 cin,cout 与 C 语言输入的同步流。在此基础上,可以用 cin.tie (0) 与 cout.tie (0) 把 cin,cout 的时间降到极致。