21xrx.com
2024-09-20 00:42:09 Friday
登录
文章检索 我的文章 写文章
C++ 基础编程实例
2023-06-23 01:57:01 深夜i     --     --
C++语言 编程实例 基础知识 数据类型 控制语句

C++ 是一种非常流行的编程语言,广泛用于各种应用和项目中。C++ 的高效、可靠和灵活使它成为许多软件开发人员的首选。C++ 的语法简单明了,易于学习和理解,因此成为许多入门级编程课程的重要组成部分。

以下是一些基础的 C++ 编程实例,帮助初学者掌握基本的编程概念和语法:

1. Hello world: 这是一个简单的程序,它能输出“Hello world”这个字符串。它是所有编程语言的入门级代码。


#include <iostream>

int main()

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

  return 0;

2. 计算器: 这个程序能够实现简单的加、减、乘和除的计算功能。


#include <iostream>

int main()

{

  int a, b, c;

  char op;

  std::cout << "Please enter the first number: ";

  std::cin >> a;

  std::cout << "Please enter the operator (+, -, *, /): ";

  std::cin >> op;

  std::cout << "Please enter the second number: ";

  std::cin >> b;

  switch(op)

  {

    case '+':

      c = a + b;

      std::cout << "Result: " << c << std::endl;

      break;

    case '-':

      c = a - b;

      std::cout << "Result: " << c << std::endl;

      break;

    case '*':

      c = a * b;

      std::cout << "Result: " << c << std::endl;

      break;

    case '/':

      if (b == 0)

      

        std::cout << "Error: division by zero" << std::endl;

      

      else

      

        c = a / b;

        std::cout << "Result: " << c << std::endl;

      

      break;

    default:

      std::cout << "Error: invalid operator" << std::endl;

      break;

  }

  return 0;

}

3. 打印乘法表: 这是一个用 C++ 编写的打印乘法表的程序。


#include <iostream>

int main()

{

  int n;

  std::cout << "Enter the number of rows: ";

  std::cin >> n;

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

  {

    for (int j = 1; j <= i; j++)

    {

      std::cout << i * j << '\t';

    }

    std::cout << std::endl;

  }

  return 0;

}

4. 转换温度单位: 这是一个简单的程序,它能够将摄氏度与华氏度互相转换。


#include <iostream>

int main()

{

  char unit;

  double temperature;

  std::cout << "Enter the temperature: ";

  std::cin >> temperature;

  std::cout << "Enter the unit (C/F): ";

  std::cin >> unit;

  if (unit == 'F' || unit == 'f')

  {

    temperature = (temperature - 32) * 5 / 9;

    std::cout << "Temperature in Celsius: " << temperature << " C" << std::endl;

  }

  else if (unit == 'C' || unit == 'c')

  {

    temperature = temperature * 9 / 5 + 32;

    std::cout << "Temperature in Fahrenheit: " << temperature << " F" << std::endl;

  }

  else

  

    std::cout << "Error: invalid unit" << std::endl;

  

  return 0;

}

这些实例程序可帮助初学者理解 C++ 编程基础知识,实践它们可帮助编程新手更好地理解和掌握编程语言的基础知识。

  
  

评论区

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