小学生零基础学C++的编程课程
作者:野牛程序员:2023-02-27 17:05:09 C++阅读 2696
欢迎来到小学生零基础学习C++编程的课程!在这个课程中,你将学习基本的编程概念和语法,并将用这些概念编写一些简单的程序。
第一课:计算器
我们将从一个简单的计算器程序开始。这个程序将提示用户输入两个数字,并执行加、减、乘、除等基本运算。
#include <iostream>
using namespace std;
int main()
{
double num1, num2;
char op;
cout << "请输入第一个数字: ";
cin >> num1;
cout << "请输入第二个数字: ";
cin >> num2;
cout << "请输入运算符 (+, -, *, /): ";
cin >> op;
double result;
switch (op)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
cout << "不支持的运算符" << endl;
return 1;
}
cout << "结果为: " << result << endl;
return 0;
}第二课:循环
下面我们来学习循环。循环是一种可以重复执行某个代码块的结构。在C++中,有两种常用的循环结构:for循环和while循环。
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "请输入一个正整数: ";
cin >> n;
// for循环
for (int i = 1; i <= n; i++)
{
cout << i << " ";
}
cout << endl;
// while循环
int j = 1;
while (j <= n)
{
cout << j << " ";
j++;
}
cout << endl;
return 0;
}第三课:函数
下面我们来学习函数。函数是一种可以接受输入参数并返回结果的代码块。在C++中,可以使用return语句返回结果。
#include <iostream>
using namespace std;
int add(int x, int y)
{
return x + y;
}
int main()
{
int a = 10, b = 20;
int c = add(a, b);
cout << "a + b = " << c << endl;
return 0;
}第四课:数组
下面我们来学习数组。数组是一种可以存储多个相同类型的元素的结构。在C++中,可以使用下标来访问数组中的元素。
#include <iostream>
using namespace std;
int main()
{
int nums[5];
for (int i = 0; i < 5; i++)
{
cout << "请输入第 " << i + 1 << " 个数字: ";
cin >> nums[i];
}
cout << "输入的数字为: ";
for (int i = 0; i < 5; i++)
{
cout << nums[i] << " ";
}
cout << endl;
return 0;
}第五课:字符串
下面我们来学习字符串。字符串是一种可以存储文本的结构。在C++中,可以使用string类型来表示字符串。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cout << "请输入一个字符串: ";
getline(cin, str);
cout << "输入的字符串为: " << str << endl;
return 0;
}第六课:结构体
下面我们来学习结构体。结构体是一种可以存储多个不同类型的元素的结构。在C++中,可以使用struct关键字定义结构体。
#include <iostream>
#include <string>
using namespace std;
struct Student
{
string name;
int age;
double score;
};
int main()
{
Student stu;
cout << "请输入学生姓名: ";
getline(cin, stu.name);
cout << "请输入学生年龄: ";
cin >> stu.age;
cout << "请输入学生分数: ";
cin >> stu.score;
cout << "学生信息:" << endl;
cout << "姓名:" << stu.name << endl;
cout << "年龄:" << stu.age << endl;
cout << "分数:" << stu.score << endl;
return 0;
}野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:零基础学C++大纲
- 下一篇:C++中STL中的迭代器
