21xrx.com
2024-12-23 00:15:43 Monday
登录
文章检索 我的文章 写文章
C++基础代码全收录
2023-06-24 05:32:40 深夜i     --     --
C++ 基础代码 全收录

C++作为一种广泛使用的编程语言,已经被广泛应用于各种领域。对于初学者来说,掌握C++基础代码是非常重要的一步,因为这是进一步学习和理解高级C++代码的基础。以下是C++基础代码的全收录。

1.输出“Hello, world!”

#include

using namespace std;

int main()

 cout << "Hello

2.输入和输出整数

#include

using namespace std;

int main()

 int num;

 cout << "Please enter an integer: ";

 cin >> num;

 cout << "The entered integer is: " << num << endl;

 return 0;

3.输入和输出浮点数

#include

using namespace std;

int main()

 float num;

 cout << "Please enter a float number: ";

 cin >> num;

 cout << "The entered float number is: " << num << endl;

 return 0;

4.输入和输出字符

#include

using namespace std;

int main()

 char ch;

 cout << "Please enter a character: ";

 cin >> ch;

 cout << "The entered character is: " << ch << endl;

 return 0;

5.if语句

#include

using namespace std;

int main()

{

 int num;

 cout << "Please enter an integer: ";

 cin >> num;

 if(num > 0)

  cout << "The entered integer is positive." << endl;

 else

  cout << "The entered integer is negative." << endl;

 return 0;

}

6.while循环

#include

using namespace std;

int main()

{

 int num = 0;

 while(num <= 10)

 {

  cout << num << endl;

  num++;

 }

 return 0;

}

7.for循环

#include

using namespace std;

int main()

{

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

  cout << i << endl;

 return 0;

}

8.数组

#include

using namespace std;

int main()

{

 int arr[5] = 2;

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

 {

  cout << arr[i] << " ";

 }

 cout << endl;

 return 0;

}

9.函数

#include

using namespace std;

int sum(int a, int b);

int main()

{

 int a, b;

 cout << "Please enter two integers: ";

 cin >> a >> b;

 int total = sum(a, b);

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

 return 0;

}

int sum(int a, int b)

{

 int result = a + b;

 return result;

}

10.类

#include

using namespace std;

class Person

{

public:

 int age;

 void display()

  cout << "The person is " << age << " years old." << endl;

};

int main()

{

 Person p;

 p.age = 20;

 p.display();

 return 0;

}

以上是C++基础代码的完整收录。掌握这些基础知识后,初学者可以更轻松地理解和阅读高级C++代码,并且更加自信地进行编程。

  
  

评论区

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