21xrx.com
2024-09-20 00:03:52 Friday
登录
文章检索 我的文章 写文章
"C++语言必背100个代码"
2023-07-03 02:33:39 深夜i     --     --
C++ 代码 必背 100个 编程技能

C++语言是一种非常流行的编程语言,已经成为程序员必备的技能之一。如果你想成为一名优秀的C++程序员,那么必须掌握C++的一些核心概念和代码。在这篇文章中,我们将分享“C++语言必背100个代码”,让你快速提升你的C++编程技能。

1. Hello world

#include

using namespace std;

int main()

  cout<<"Hello World!"<

  return 0;

这是C++程序员必须学习的第一个程序,它可以输出“Hello World!”的信息。

2. 计算两个整数的和

#include

using namespace std;

int main()

{

  int a, b, c;

  cin>>a>>b;

  c=a+b;

  cout< <

  return 0;

}

这段代码可以让你计算出两个整数的和。

3. 判断一个数是否为正数

#include

using namespace std;

int main()

{

  int a;

  cin>>a;

  if(a > 0)

    cout<<<"是正数"<

  else

    cout<<<"不是正数"<

  return 0;

}

这个代码片段会告诉你如何判断一个数是否是正数。

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

#include

using namespace std;

int main()

{

  int a;

  cin>>a;

  if(a % 2 == 0)

    cout<<<"是偶数"<

  else

    cout<<<"不是偶数"<

  return 0;

}

这个代码片段会告诉你如何判断一个数是否为偶数。

5. 查找最大值

#include

using namespace std;

int main()

{

  int a, b, c, max;

  cin>>a>>b>>c;

  max=a>b?a:b;

  max=max>c?max:c;

  cout<<"最大值是:"< <

  return 0;

}

这个代码片段会告诉你如何查找三个数中的最大值。

6. 计算数组的平均值

#include

using namespace std;

int main()

{

  int a[10], sum=0;

  float avg;

  for(int i=0; i<10; i++)

    cin>>a[i];

  for(int i=0; i<10; i++)

    sum += a[i];

  avg=(float)sum/10;

  cout<<"平均值是:"< <

  return 0;

}

这个代码片段会让你计算一个数组的平均值。

7. 字符串大小写转换

#include

#include

#include

#include

using namespace std;

int main()

{

  char str[20];

  cin>>str;

  for(int i=0; i

    if(islower(str[i]))

      str[i]=toupper(str[i]);

    else if(isupper(str[i]))

      str[i]=tolower(str[i]);

  }

  cout<<"转换后的字符串是:"< <

  return 0;

}

这段代码可以将一个字符串中的所有小写字母转换为大写字母,并将所有大写字母转换为小写字母。

8. 冒泡排序

#include

using namespace std;

int main()

{

  int a[10];

  for(int i=0; i<10; i++)

    cin>>a[i];

  for(int i=0; i<9; i++){

    for(int j=0; j<9-i; j++){

      if(a[j]>a[j+1]){

        int temp=a[j];

        a[j]=a[j+1];

        a[j+1]=temp;

      }

    }

  }

  cout<<"排序后的数组是:"<

  for(int i=0; i<10; i++)

    cout< <<" ";

  cout<

  return 0;

}

这个代码片段可以执行冒泡排序,让你在排序一个数组时更加有效率。

9. 计算一个字符串中字符的个数

#include

#include

using namespace std;

int main()

{

  char str[50];

  cin>>str;

  int len=strlen(str), count=0;

  for(int i=0; i

    if(str[i]!=' ')

      count++;

  }

  cout<<"字符串中的字符数量是:"< <

  return 0;

}

这个代码片段可以帮助你计算字符串中的字符数量,包括空格。

以上是我们分享的“C++语言必背100个代码”,这些代码片段是C++程序员必须学会的核心概念和代码。我们希望这些代码对你的C++编程能力有所提升。

  
  

评论区

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