一、结构体
属于用户自定义的数据类型,允许用户存储不同的数据类型
语法:struct 结构体名 {结构体成员列表};(定义)
通过结构体创建变量的三种方式:
1、struct 结构体名 变量名
2、struct 结构体名 变量名={成员1,成员2……}
3、定义结构体时顺便创建变量(不常用)
创建的时候struct可以省略,定义的时候不可以省略
//1.创建学生数据类型
struct student
{
string name;
int age;
int sorce;
}s3;
//2.通过学生类型创建具体学生
int main()
{
//2.1
struct student s1;
//给s1属性赋值,通过.访问结构体变量中的属性
s1.name = "张三";
s2.age = 18;
s2.sorce = 100;
cout << s1.name << s1.age << s1.sorce << endl;
//2.2
struct student = {"李四",19,80};
cout << s2.name << s2.age << s2.sorce << endl;
//2.3
s3.name = "王五";
s3.age = 20;
s3.sorce = 60;
cout << s3.name << s3.age << s3.sorce << endl;
return 0;
}
二、结构体数组
作用:将定义的结构体放入到数组中方便维护
语法:struct 结构体名 数组名 [元素个数] = {{},{},……{}}//struct 结构体名 相当于一个数据类型
与数组相似
struct student
{
string name;
int age;
int sorce;
};
int main()
{
struct student arr[3] =
{
{"张三",18,100},{"李四",28,99},{"王五",38,66}
};//初始化的值
for(int i = 0;i < 3;i++)
{
cout << arr[3].name << arr[3].age << arr[3].sorce << endl;
}
return 0;
}
三、结构体指针
作业:通过指针访问结构体中的成员
利用操作符->可以通过结构体指针访问结构体属性
struct student//定义学生的结构体
{
string name;
int age;
int sorce;
};
int main()
{
//1.创建学生结构体变量
struct student s = {“张三”,18,100};
//2.通过指针指向结构体变量
struct student *p = &s;
//3.通过指针访问结构体变量中的数据(->)
cout << p -> name << p -> age << p -> sorce << endl;
return 0;
}
四、结构体嵌套结构体
作用:结构体中的成员可以是另一个结构体
例如:每个老师辅导一个学员,一个老师的结构体中记录一个学生的结构体
//学生结构体定义
struct student
{
string name;
int age;
int sorce;
};
//老师的结构体定义
struct teacher
{
int id;
string name;
int age;
struct student s;
};
int main()
{
struct teacher t;
t.id = 10000;
t.name = "老王";
t.age = 50;
t.s.name = "小王";
t.s.age = 20;
t.s.sorce =80;
cout << t.id << t.name << t.age << t.s.name << t.s.age << t.s.age << t.s.sorce << endl;
return 0;
}
五、结构体做函数参数
作用:将结构体作为参数向函数中传递
传递方式有两种:1.值传递 2.地址传递
struct student
{
string name;
int age;
int sorce;
};
//值传递
void printstudent1(student s)
{
//形参改变对实参不造成影响
s.age = 28;
cout << "子函数中姓名:" << s.name <<s.age << s.sorce << endl;
}
//地址传递
void printstudent2(student *s)
{
s -> age = 28;
cout << "子函数中的姓名:" << s -> naame << s -> age << s -> sorce << endl;
}
int main()
{
student s = {"张三",18,100};
//值传递
printstudent1(s);
//地址传递
printstudent2(&s);
cout << s.name << s.age << s.sorce << endl;
return 0;
}
六、结构体中const使用场景
作用:用const来防止误操作
struct student
{
string name;
int age;
int sorce;
};
//const使用场景
void printstudent(const student*s)//将函数中的形参改为指针,减少了内存空间,指针只占4个字节
{
//s -> age = 100;//操作失败,因为加了const修饰
cout << s -> name << s -> age << s->sorce << endl;
}
int main()
{
student s = {“张三”,18,100};
printstudent(&s);
return 0;
}
七、案例
学生正在做毕设项目,每名老师带领5个学生,总共有3名老师,需求如下
设计学生和老师的结构体,其中在老师的结构体中,有老师姓名和一个存放5名学生的数组作为成员,学生的成员有姓名和考试分数,创建数组存放3名老师,通过函数给每名老师及所带的学生赋值,最终打印出老师的数据及老师所带学生的数据。
#include<iostream>
using namespace std;
struct student
{
string sname;
int score = 0;
};
struct techer
{
string tname;
struct student sarray[5];
};
void allocatespace(struct techer tarray[], int len)
{
string nameseed = "ABCDE";
for (int i = 0;i < len; i++)
{
tarray[i].tname = "techer_";
tarray[i].tname += nameseed[i];
for (int j = 0;j < 5; j++)
{
tarray[i].sarray[j].sname = "student_";
tarray[i].sarray[j].sname += nameseed[j];
int random = rand() % 61 + 40;
tarray[i].sarray[j].score = random;
}
}
}
void printinfomation(struct techer tarray[], int len)
{
for (int i = 0;i < len; i++)
{
cout << "老师的姓名: " << tarray[i].tname << endl;
for (int j = 0;j < 5; j++)
{
cout << "\t" << tarray[i].sarray[j].sname << " " << tarray[i].sarray[j].score << endl;
}
}
}
int main()
{
//随机数种子
srand((unsigned int)time(NULL));
//1、创建3名老师的数组
struct techer tarray[3];
//2、通过函数给3名老师的信息赋值,并给老师带的学生的信息赋值
int len = sizeof(tarray) / sizeof(tarray[0]);
allocatespace(tarray, len);
//3、打印所有老师及学生的信息
printinfomation(tarray, len);
system("pause");
return 0;
}
设计一个英雄的结构体,包括成员姓名、年龄、性别。创建结构体数组,数组中存放5名英雄,通过冒泡排序的算法,将数组中的英雄按照年龄进行升序排序,最终打印排序后的结果,五名英雄的信息如下:
{“刘备”,23,”男“},
{”关羽“,22,”男“},
{”张飞“,20,”男“},
{”赵云“,21,”男“},
{”貂蝉“,19,”女“};
#include<iostream>
using namespace std;
struct hero
{
string name;
int age;
string sex;
};
//冒泡排序,实现年龄的升序
void bubblesort(struct hero arr[],int len)
{
for(int i = 0;i < len-1;i++)
{
for(int j = 0;j < len-i-1;j++)
{
if(arr[j].age > arr[j+1].age)
{
struct hero temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
void printhero(struct hero arr[],int len)
{
for(int i = 0;i < len;i++)
{
cout << arr[i].name << arr[i].age << arr[i].sex << endl;
}
}
int main()
{
//创建数组存放5名英雄
struct hero arr[5]=
{
{“刘备”,23,”男“},
{”关羽“,22,”男“},
{”张飞“,20,”男“},
{”赵云“,21,”男“},
{”貂蝉“,19,”女“}
};
int len = sizeof(arr)/sizeof(arr[0]);
cout << "排序前打印为:" << endl;
for(int i = 0;i < len;i++)
{
cout << arr[i].name << arr[i].age << arr[i].sex << endl;
}
bubblesort(arr,len);
cout << "排序后打印为:" << endl;
printhero(arr.len);
return 0;
}
八、题目
题目描述
一个最简单的计算器,支持+, -, *, / 四种运算。
输入
输入只有一行,共有三个参数,其中第1、2个参数为操作数,第3个参数为操作码(+,-,*,/)。
输出
输出只有一行,为运算结果, 保留两位小数。然而:
1. 如果出现除数为0的情况,则输出:Divided by zero!
2. 如果出现无效的操作符(即不为 +, -, *, / 之一),则输出:Invalid operator!
以下是两种方法:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double num1, num2;
char s;
cin >> num1 >> num2 >> s;
double result;
bool error = false;//这里的意思是定义一个名为 error 的变量,并且初始状态下表示没有错误发生
string errorMessage;
switch (s)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 == 0)
{
error = true;//表示有错误发生
errorMessage = "Divided by zero!";
}
else
{
result = num1 / num2;
}
break;
default:
error = true;//表示有错误发生
errorMessage = "Invalid operator!";
break;
}
if (error)//指的是有错误发生
{
cout << errorMessage << endl;
}
else
{
cout << fixed << setprecision(2) << result << endl;
}
return 0;
}
include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double num1, num2;
char s;
cin >> num1 >> num2 >> s;
double result;
bool error = false;
string errorMessage;
if (s == '+') {
result = num1 + num2;
}
else if (s == '-') {
result = num1 - num2;
}
else if (s == '*') {
result = num1 * num2;
}
else if (s == '/') {
if (num2 == 0) {
error = true;
errorMessage = "Divided by zero!";
}
else {
result = num1 / num2;
}
}
else {
error = true;
errorMessage = "Invalid operator!";
}
if (error) {
cout << errorMessage << endl;
}
else {
cout << fixed << setprecision(2) << result << endl;
}
return 0;
}
Wif the alphabet is a vowel,output:The alphabet is a vowel.rite a C program to check whether an alphabet is a vowel or a consonant.
Input:
Input an alphabet.
if the alphabet is a vowel,output:The alphabet is a vowel.
if the alphabet is a consonant,output:The alphabet is a consonant.
or,output:The alphabet is not a consonant.
Output:
print whether an alphabet is a vowel or consonant.
if the alphabet is a vowel,output:The alphabet is a vowel.
Sample Input & Output:
Input an alphabet: a
The alphabet is a vowel.
#include <iostream>
#include <cctype>
using namespace std;
int main() {
char ch;
cout << "Input an alphabet: ";
cin >> ch;
if (!isalpha(ch))
{
cout << "The alphabet is not a consonant." << endl;
}
else
{
ch = tolower(ch);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
cout << "The alphabet is a vowel." << endl;
}
else
{
cout << "The alphabet is a consonant." << endl;
}
}
return 0;
}
Write a C program to check the Armstrong number of n digits.
Note: An n-digit number that is the sum of the nth powers of its digits is called an Armstrong number.
Examples : 153 =1^3+5^3+3^3 ; 1634 = 1^4+6^4+3^4+4^4.
Input:
Input an integer.
Output:
Output whether the number is an Armstrong number or not.
Sample Input & Output:
Input an integer: 153
153 is an Armstrong number.
#include<iostream>
#include<cmath>
using namespace std;
//函数的使用
int countDigits(int num)
{
int n = 0;
while (num != 0)
{
num /= 10;
n++;
}
return n;
}
int main()
{
int num;
cout << "Input an integer: ";
cin >> num;
int n = countDigits(num);
int remainder;
double result = 0.0;//初始话result
int originalnum = num;
while (num != 0)
{
remainder = num % 10;
result += pow(remainder, n);
num /= 10;
}
if (result == originalnum)
{
cout << originalnum << " is an Armstrong number." << endl;
}
else
{
cout << originalnum << " is not an Armstrong number." << endl;
}
return 0;
}
题目描述
用迭代法求 。求平方根的迭代公式为:
要求前后两次求出的得差的绝对值少于0.00001。 输出保留3位小数
输入
a
输出
a的平方根
//使用牛顿迭代法计算平方根的C++程序
#include <iostream>
#include <iomanip>
#include <cmath> // 使用 fabs 函数
using namespace std;
int main() {
double a;
cout << "输入 a: ";
cin >> a;
if (a < 0)
{
cout << "负数没有实数平方根。" << endl;
return 1;
}
double tolerance = 0.00001;
double guess = a / 2.0; // 初始猜测值
/*
在牛顿迭代法中,选择一个合理的初始猜测值非常重要。
对于求解 a,选择 a/2 作为一个简单的初始猜测值是一个常见的做法,原因如下:
简单性:a/2 易于计算且容易理解。
合理性:对于大多数正数 a,a/2 是一个相对合理的初始猜测值。例如,如果 a=4,那么 a/2=2,这是一个正确的平方根。
收敛性:牛顿迭代法通常在合理的选择下快速收敛到正确答案。
*/
double newGuess;
do {
newGuess = (guess + a / guess) / 2.0; // 牛顿迭代公式
if (fabs(newGuess - guess) < tolerance) { // 检查是否满足容差条件
break;
}
guess = newGuess; // 更新猜测值
} while (true);
/*
while (true) 表示只要条件为真,就不断执行循环体内的代码。
这种形式的循环不会自然终止,因此必须在循环体内提供一个明确的退出机制(例如 break 语句),否则会导致无限循环。
*/
cout << fixed << setprecision(3) << "a 的平方根是 " << newGuess << endl; // 输出结果,保留三位小数
return 0;
}
Write a C/C++ program to check whether a number is a Strong Number or not. A strong number is a positive integer whose sum of factorials of its digits equals the number itself. For example, 145 is such a number because 1! + 4! + 5! = 1 + 24 + 120 = 145.
Input:
Input a positive integer.
Output:
Output whether a positive integer is a Strong Number.
Sample Input & Output:
Input a positive integer: 145
145 is a Strong number.
Input a positive integer: 520
520 is not a Strong number.
//C++ 程序检查一个数是否为强数
#include<iostream>
#include<cmath>
using namespace std;
// 计算阶乘的函数,使用 tgamma 函数来计算
int factorial(int num) {
return tgamma(num + 1); // tgamma(n+1) 返回 n!
}
// 检查一个数是否为强数的函数
void Strongnumber(int num) {
int originalNum = num; // 保存原始数字
int sum = 0; // 初始化累加和
// 循环处理每个数字的每一位
while (num > 0) {
int digit = num % 10; // 获取当前位上的数字
sum += factorial(digit); // 将该位数字的阶乘加到累加和中
num /= 10; // 去掉最后一位数字
}
// 判断累加和是否等于原始数字
if (sum == originalNum) {
cout << originalNum << " 是一个强数。" << endl;
}
else {
cout << originalNum << " 不是一个强数。" << endl;
}
}
int main() {
int num;
cout << "请输入一个正整数: ";
cin >> num;
Strongnumber(num);
return 0;
}
Write a program in C/C++ to check whether a number is a Mersenne Prime number or not using the function.
Mersenne prime numbers are numbers of the form m =2p-1 , where m shuold be prime,and p itself must be prime.
Input:
Input a positive number.
Output:
Output whether the number is Mersenne prime number or not.
Sample Input & Output:
Input a positive number: 31
31 is a Mersenne prime number.
//C++ 程序检查一个数是否为梅森素数
#include <iostream>
#include <cmath>
using namespace std;
// 函数检查一个数是否为素数
bool prime(int num)
{
if (num <= 1) return false;
if (num == 2) return true;
if (num % 2 == 0) return false;
for (int i = 3; i * i <= num; i += 2)
{
if (num % i == 0) return false;
}
return true;
}
// 函数检查一个数是否为梅森素数
void mersenneprime(int m)
{
if (m < 2)
{
cout << m << " is not a Mersenne prime number." << endl;
}
// 找到 p 使得 m = 2^p - 1
int p = 1;
while ((1LL << p) - 1 <= m)//1LL << p 表示将数字 1 左移 p 位,相当于计算2^p,(1LL << p)等价于2^p
{
if ((1LL << p) - 1 == m)
{
// 检查 p 是否为素数
if (prime(p))
{
cout << m << " is a Mersenne prime number." << endl;
}
}
p++;
}
cout << m << " is not a Mersenne prime number." << endl;
}
int main()
{
int m;
cout << "Input a positive number: ";
cin >> m;
mersenneprime(m);
return 0;
}
分式约分是把一个分数的分子、分母同时除以公约数,分数的值不变,这个过程叫约分。请编写一个程序把分数化成最简分数。
输入格式
一行,按a/b 格式输入一个分数,a,b 都为整数,a为分子,b为分母。
输出格式
一行,按a/b 格式输出一个最简分数。
样例输入 #1
9/15
样例输出 #1
3/5
#include<iostream>
using namespace std;
//求最大公约数
int gcd(int a, int b)
{
while (b != 0)
{
int temp = b;
b = a % b;
a = temp;
}
return a;
}
void simplifynumber(int &a, int &b)
{
int c = gcd(a, b);//最大公约数
a /= c;
b /= c;
}
int main()
{
int a, b;
cin >> a >> b;
simplifynumber(a, b);
cout << a << "/" << b << endl;
return 0;
}
Write a program in C/C++ to check whether two given strings are an anagram.
Note: An anagram is a word or phrase formed by rearranging the letters in another word or phrase.
Anagram Examples:
Spare | Pears |
George Bush | He bugs Gore |
Presbyterian | best in prayer |
Input:
Input two words or phrases.
Output:
Output whether two given strings are an anagram. The give string is case-insensitive and ignoring non-letters.
Sample Input & Output:
Input the first String: Spare
Input the second String: Pears
Spare and Pears are Anagram.
//检查两个字符串是否为字母异位词
#include<iostream>//包含输入输出流
#include<algorithm>//包含sort
#include<cctype>//包含isalpha和tolower
#include<string>//包含string的头文件
using namespace std;
// 辅助函数:处理字符串,移除非字母字符并转换为小写
string preprocess(const string& str)
{
string result;
for (char ch : str)
{
// 检查字符是否为字母
if (isalpha(ch))
{
result += tolower(ch); // 转换为小写并添加到结果中
}
}
return result;
}
// 函数:判断两个字符串是否为字母异位词
bool areAnagrams(const string& str1, const string& str2)
{
// 处理两个字符串
string processedstr1 = preprocess(str1);
string processedstr2 = preprocess(str2);
// 对处理后的字符串进行排序,排序后的字符串将按字典顺序排序
sort(processedstr1.begin(), processedstr1.end());
sort(processedstr2.begin(), processedstr2.end());
// 比较排序后的字符串
return processedstr1 == processedstr2;
}
int main() {
string str1, str2;
cout << "输入第一个字符串: ";
getline(cin,str1);
cout << "输入第二个字符串: ";
getline(cin,str2);
if (areAnagrams(str1, str2)) {
cout << str1 << " 和 " << str2 << " 是字母异位词。" << endl;
}
else {
cout << str1 << " 和 " << str2 << " 不是字母异位词。" << endl;
}
return 0;
}