21xrx.com
2024-11-22 09:28:55 Friday
登录
文章检索 我的文章 写文章
C++简单代码集锦
2023-06-22 06:32:52 深夜i     --     --
C++ 代码 集锦 简单实现 编程语言

C++是一种跨平台的编程语言,在许多领域都有广泛的应用。这里为大家整理了一些C++的简单代码,供入门学习或实际使用。

1. 输出Hello World!


#include <iostream>

int main()

  std::cout << "Hello World!" << std::endl;

  return 0;

2. 输入和输出


#include <iostream>

int main()

  int x;

  std::cout << "Please enter an integer: ";

  std::cin >> x;

  std::cout << "The number you entered is " << x << std::endl;

  return 0;

3. 求两个数的和


#include <iostream>

int main()

{

  int a, b, sum;

  std::cout << "Please enter two integers: ";

  std::cin >> a >> b;

  sum = a + b;

  std::cout << "The sum of " << a << " and " << b << " is " << sum << std::endl;

  return 0;

}

4. 判断一个数是否为偶数


#include <iostream>

int main()

{

  int x;

  std::cout << "Please enter an integer: ";

  std::cin >> x;

  if (x % 2 == 0)

    std::cout << x << " is even" << std::endl;

  

  else

    std::cout << x << " is odd" << std::endl;

  

  return 0;

}

5. 判断一个年份是否为闰年


#include <iostream>

int main()

{

  int year;

  std::cout << "Please enter a year: ";

  std::cin >> year;

  if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)

    std::cout << year << " is a leap year" << std::endl;

  

  else

    std::cout << year << " is not a leap year" << std::endl;

  

  return 0;

}

6. 计算n的阶乘


#include <iostream>

int main()

{

  int n, factorial = 1;

  std::cout << "Please enter an integer: ";

  std::cin >> n;

  for (int i = 1; i <= n; i++) {

    factorial *= i;

  }

  std::cout << n << "! = " << factorial << std::endl;

  return 0;

}

7. 计算斐波那契数列的第n项


#include <iostream>

int main()

{

  int n;

  std::cout << "Please enter an integer: ";

  std::cin >> n;

  int a = 0, b = 1, c;

  for (int i = 2; i <= n; i++) {

    c = a + b;

    a = b;

    b = c;

  }

  std::cout << "The " << n << "th Fibonacci number is " << b << std::endl;

  return 0;

}

以上代码只是C++语言的冰山一角,学习C++需要不断积累,不断实践,才能够掌握这门语言。希望大家加油!

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复