2023
判断程序输出
这里结果是
runtime_error
errorA
errorB
errorA
这里出现了两个问题
1.首先,先AB是runtime的基类,C是A的基类是runtime间接基类,catch是按顺序捕获,防止ABC被捕获先把catch(runtime)放在后面
ErrorA和B在构造的时候覆盖了 runtime_error
的构造函数以提供特定的错误消息
what函数是用来输出构造函数初始化对象的时候输进去的那个string变量的
2.ErrorC 应该是没有输进去,是指单纯的调用了一下 runtime_error 的构造函数
case0 最下面的runtime_error捕获
case1 ErrorA捕获what输出
case2 ErrorB捕获what输出
case3 ErrorA捕获what输出
#include <iostream>
#include <stdexcept>
using namespace std;
class ErrorA : public runtime_error {
public:
ErrorA() : runtime_error("errorA") {}
};
class ErrorB : public runtime_error {
public:
ErrorB() : runtime_error("errorB") {}
};
class ErrorC : public ErrorA {
public:
ErrorC(){runtime_error{"errorC"}; } // 调用基类ErrorA的构造函数 A中将runtime_error设为 errorA
};
int main() {
for (int i = 0; i < 4; i++) {
try {
switch (i) {
case 0: throw runtime_error("runtime_error"); break; // 正确抛出runtime_error实例
case 1: throw ErrorA(); // 正确使用ErrorA类名
case 2: throw ErrorB(); // 正确使用ErrorB类名
case 3: throw ErrorC(); // 正确使用ErrorC类名
}
}
catch (ErrorA& err) {
cout << err.what() << endl;
} catch (ErrorB& err) {
cout << err.what() << endl;
} catch (ErrorC& err) {
cout << err.what() << endl;
}
catch (runtime_error& err) {
cout << err.what() << endl;
}
//ErrorC 是从 ErrorA 继承的,而 ErrorA 是从 runtime_error 继承的。ErrorC 是 runtime_error 的间接派生类
//ErrorC 可以被任何能够引用其基类或派生类类型的catch块捕获
}
return 0;
}
先看问题2 如果我们把catch C的顺序调到A前 输出还是不变 因为C是A的派生类先析构基类,生成基类对象被catchA截获,ErrorC 应该是没有输进去,是指单纯的调用了一下 runtime_error 的构造函数生成了一个新对象
修改如下
catch (ErrorC& err) {
cout << err.what() << endl;
} catch (ErrorB& err) {
cout << err.what() << endl;
} catch (ErrorA& err) {
cout << err.what() << endl;
}
catch (runtime_error& err) {
cout << err.what() << endl;
}
输出
runtime_error
errorA
errorB
errorA
这里举个例子上面的是正确的 下面是错误的
class ErrorA : public runtime_error {
public:
ErrorA():runtime_error("ErrorA") {}
};
class ErrorA : public runtime_error {
public:
ErrorA(){runtime_error("Error A");
}
};
在下面这个构造函数中,runtime_error("Error A")
实际上创建了一个临时的runtime_error
对象,这个对象并没有被用来初始化ErrorA
对象,而是被立即丢弃了。因此,ErrorA
对象仍然会使用runtime_error
的默认构造函数进行初始化,这通常会导致它包含一个空字符串或者默认的异常描述。
所以要正确输出errorC 需要构造函数应该初始化其基类 ErrorA从而间接修改
runtime_error 的构造函数
修改重新定义ErrorA的构造函数 并在C中初始化A
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;
class ErrorA : public runtime_error {
public:
ErrorA() : runtime_error("errorA") {}
ErrorA(string s) : runtime_error(s) {};
};
class ErrorB : public runtime_error {
public:
ErrorB() : runtime_error("errorB") {}
};
class ErrorC : public ErrorA {
public:
//ErrorC(){runtime_error{"errorC"}; } // 调用基类ErrorA的构造函数 A中将runtime_error设为 errorA
//what函数是用来输出构造函数初始化对象的时候输进去的那个string变量的
//ErrorC 应该是没有输进去,是指单纯的调用了一下 runtime_error 的构造函数
ErrorC() : ErrorA("errorC specific") {} //基类A生成初始化被改变
};
int main() {
for (int i = 0; i < 4; i++) {
try {
switch (i) {
case 0: throw runtime_error("runtime_error"); break; // 正确抛出runtime_error实例
case 1: throw ErrorA(); // 正确使用ErrorA类名
case 2: throw ErrorB(); // 正确使用ErrorB类名
case 3: throw ErrorC(); // 正确使用ErrorC类名
}
}
catch (ErrorC& err) {
cout << err.what() << endl;
} catch (ErrorB& err) {
cout << err.what() << endl;
} catch (ErrorA& err) {
cout << err.what() << endl;
}
catch (runtime_error& err) {
cout << err.what() << endl;
}
//ErrorC 是从 ErrorA 继承的,而 ErrorA 是从 runtime_error 继承的。ErrorC 是 runtime_error 的间接派生类
//ErrorC 可以被任何能够引用其基类或派生类类型的catch块捕获
}
return 0;
}
这里捕获可以只留下runtime因为catch可以捕获基类的派生类
PS:这里改变捕获AC的顺序 输出顺序也不会改变 因为C在本质上改变了A中runtime初始化
所以这道题实际上没考到catch顺序的问题,举个catch顺序例题 没找到
2019
1.selfString 类实现(不能使用标准模板库)
(1)两个数据成员: char* dataStr (存储英文句子),int Length(英文句子长度)
(2)至少实现两个成员函数:构造函数(从文件中读取一段英文句子),析构函数
(3)待实现:用友元函数实现求两个英文句子的最长公共单词( 单词以空格区分,如hello world这个英文句子有两个单词hello 和world )
自己写的在主函数中实现输入流
#include<iostream>
#include<cstring>
#include<fstream>
using namespace std;
class selfString
{
public:
selfString():dataStr(NULL),Length(0){}
selfString(char *p,int n):dataStr(new char[n]),Length(n){//这里直接在dataStr里new空间而不是调用p
strcpy(dataStr,p);
cout<<"the sentence is "<<dataStr<<endl;
}
~selfString(){
cout<<"finish reading "<<dataStr<<endl;
delete[] dataStr;
}
friend const char* longest(const selfString s1,const selfString s2);
int getlen()const{
return Length;
}
const char* getData() const {
return dataStr;
}
private:
char* dataStr;
int Length;
};
int main() {
ifstream myFile("data.txt");
if (!myFile) {
cerr << "Error opening file!" << endl;
return 1;
}
// 读取文件内容到字符串中
const int BUFFER_SIZE = 1024; // 缓冲区大小
char buffer[BUFFER_SIZE];
while (myFile.good()) { //myFile.good()检查流的状态是否良好
myFile.getline(buffer, BUFFER_SIZE); // getline读取一行
}
myFile.close();
// 构造 selfString 对象
selfString str(buffer, strlen(buffer)); // 使用 string 的内容构造 selfString 对象
}
这里对C语言的输入输出流还不熟练,需要再学习一下
getline()是string流的函数,只能用于string类型的输入操作。当你定义了一个string类型变量,只能用getline()来输入。
cin.getline是std流的函数,用于char类型的输入操作。当你定义了一个char类型变量,只能用cin/cin.getline()输入。
原文链接:https://blog.csdn.net/PuddleRubbish/article/details/128410616
- getline(储存的数组名,长度,终止符)
- getline(cin,接受的string变量) //加头文件#include<string.h>
- get(ch) //a=cin.get() while(cin.get(c))
- get(数组,个数,终止符) //cin.get(a, strlen(a), '*');
参考别人在构造函数中输入 巧妙的把文件名设为析构的输入
#include<iostream>
#include<fstream>
using namespace std;
class selfstring
{
char* datastr;
int length;
public:
selfstring(char* d, int l)
{
datastr = new char[l];
char ch;
int i = 0;
fstream file(d);
if (!file) { cout << "文件无法打开"; }
file.getline(datastr, l);
length = strlen(datastr);
}
~selfstring() { delete[] datastr; }
friend void jiaoji(selfstring s1, selfstring s2);
void show() { cout << datastr << endl; }
};
int main(void)
{
char a []= "data.txt";
selfstring s1(a, 20);
s1.show();
}
2. switch输出
注意case后面有无break cout endl不要忘看
#include<iostream>
using namespace std;
int main()
{
int a=4,c=0,b=1;
for(int i=0;i<5;++i)
{
switch((--a)>0)
{
case 0:switch(c++)
{
case 0:cout<<"%";
case 1:cout<<"#";
}break;
case 1:switch(b)
{
case 0:cout<<"*";--b;break;
case 1:cout<<"@";--b;break;
}
default:cout<<"&";
}
cout<<"!"<<endl;
}
return 0;
}
输出
@&!
*&!
&!
%#!
#!
3.考察作用域
此处有两个i 第二个i出了for就消失了
#include<iostream>
using namespace std;
void func(int a)
{
cout<<a<<endl;
}
int main()
{
int i=0,k=2;
for(int i=1;i<=3;++i)
{
func(i*k);
}
cout<<i<<" "<<k<<endl;
return 0;
}
输出
2
4
6
0 2
4.传参
这里只是吧pq 新建对象局部变量的值交换 并没有交换pa和pb
void func(int* &p,int* &q)使用引用就可以实现交换
#include<iostream>
using namespace std;
void func(int* p,int* q)
{
int *c;
c=p;
p=q;
q=c;
}
int main()
{
int a=7,b=19;
int *pa=&a,*pb=&b;
cout<<*pa<<" "<<*pb<<endl;
func(pa,pb);
cout<<*pa<<" "<<*pb<<endl;
return 0;
}
输出
7 19
7 19
5.区分字符串的\0 和数组的0
#include<iostream>
using namespace std;
void func(char str[])
{
int count= 0;
while (*str != 0)
{
if(*str>='0' && *str<='9')
count++;
str++;
}
cout << count << endl;
}
int main()
{
char str[] = "abc8d0e32fg\0hi1k3";
func(str);
return 0;
}
输出4
6.全局对象、静态局部对象、栈对象的构造与析构的调用顺序问题。
全局变量的初始化要在 main 函数执行前完成
静态局部对象在main结束最后析构 再多做点此类的题
#include<iostream>
using namespace std;
class A
{
public:
A(int x):xx(x)
{
cout<<"A()"<<xx<<endl;
}
~A()
{
cout<<"~A()"<<xx<<endl;
}
private:
int xx;
};
A a(1);
int main()
{
A b(2);
static A c(3);
return 0;
}
A m(6);
A()1
A()6
A()2
A()3
~A()2
~A()3
~A()6
~A()1
7.考察前置++运算符设置为友元函数,这题的坑在于,返回值是不是对象的引用,形参也不是对象的引用,导致自增离开了作用域以后就不在有任何效果。
太细了 防不胜防
10,20
10,20
8.虚函数
这里print是虚函数 通过基类指针调用派生类 会覆盖定义 但是注意析构函数不是虚函数 会导致没有析构派生类 释放派生类的内存 内存泄漏
#include<iostream>
using namespace std ;
class A
{
public :
A()
{
cout<<"A() "<<endl ;
}
virtual void print()const{
cout<<"I am A" <<endl ;
}
~A()
{
cout<<"~A()"<<endl;
}
};
class B:public A{
public:
B(){
cout<<"B()"<<endl;
}
void print()const
{
cout<<"I am B"<<endl;
}
~B()
{
cout<<"~B()"<<endl ;
}
};
int main()
{
A *pa=new B();
pa->print();
delete pa;
return 0 ;
}
A()
B()
I am B
~A()
改为 vitual ~A()
A()
B()
I am B
~B()
~A()
抽象类
作用:抽象类为抽象和设计的目的而声明,将有关的数据和行为组织在一个继承层次结构中,保证派生类具有要求的行为。 对于暂时无法实现的函数,可以声明为纯虚函数,留给派生类去实现。 注意:
- 抽象类只能作为基类来使用。
- 不能声明抽象类的对象。
- 构造函数不能是虚函数,析构函数可以是虚函数。
Base1抽象类 使用纯虚函数
//8_6.cpp
#include <iostream>
using namespace std;
class Base1 { //基类Base1定义
public:
virtual void display() const = 0; //纯虚函数
};
class Base2: public Base1 { //公有派生类Base2定义
public:
void display() const; //覆盖基类的虚函数
};
void Base2::display() const {
cout << "Base2::display()" << endl;
}
class Derived: public Base2 { //公有派生类Derived定义
public:
void display() const; //覆盖基类的虚函数
};
void Derived::display() const {
cout << "Derived::display()" << endl;
}
void fun(Base1 *ptr) { //参数为指向基类对象的指针
ptr->display(); //"对象指针->成员名"
}
int main() { //主函数
Base2 base2; //定义Base2类对象
Derived derived; //定义Derived类对象
fun(&base2); //用Base2对象的指针调用fun函数
fun(&derived); //用Derived对象的指针调用fun函数
return 0;
}
//运行结果:
//Base2::display()
//Derived::display()
使用dynamic_cast
语法形式 dynamic_cast<目的类型>(表达式) 功能 将基类指针转换为派生类指针,将基类引用转换为派生类引用; 转换是有条件的 如果指针(或引用)所指对象的实际类型与转换的目的类型兼容,则转换成功进行(基类指针指向的是派生类才能转换为派生类指针); 否则如执行的是指针类型的转换,则得到空指针;如执行的是引用类型的转换,则抛出异常。
//8_9.cpp
#include <iostream>
using namespace std;
class Base {
public:
virtual void fun1() { cout << "Base::fun1()" << endl; }
virtual ~Base() { }
};
class Derived1: public Base {
public:
virtual void fun1() { cout << "Derived1::fun1()" << endl; }
virtual void fun2() { cout << "Derived1::fun2()" << endl; }
};
class Derived2: public Derived1 {
public:
virtual void fun1() { cout << "Derived2::fun1()" << endl; }
virtual void fun2() { cout << "Derived2::fun2()" << endl; }
};
void fun(Base *b) {
b->fun1();
Derived1 *d = dynamic_cast<Derived1 *>(b); //尝试将b转换为Derived1指针 指针地址还是其派生类
if (d != 0) d->fun2(); //判断转换是否成功
}
int main() {
Base b;
fun(&b);
Derived1 d1;
fun(&d1);
Derived2 d2;
fun(&d2);
return 0;
}
//运行结果:
//Base::fun1() 这里base的&b是基类 若base指针指向派生类可以转换指针
//Derived1::fun1()
//Derived1::fun2()
//Derived2::fun1()
//Derived2::fun2()
#include <iostream>
using namespace std;
class Base {
public:
virtual ~Base() {} // 虚析构函数确保多态性正确工作
};
class Derived1 : public Base {
public:
void print() { cout << "Derived1" << endl; }
};
void checkType(Base* basePtr) {
Derived1* derived1Ptr = dynamic_cast<Derived1*>(basePtr);
if (derived1Ptr != nullptr) {
// 转换成功,可以安全地使用 derived1Ptr
derived1Ptr->print();
} else {
// 转换失败,basePtr 不指向 Derived1 对象
cout << "The pointer does not point to a Derived1 object." << endl;
}
}
int main() {
Base* basePtr = new Base(); // 指向 Base 对象的指针
checkType(basePtr); // 输出 "The pointer does not point to a Derived1 object."
delete basePtr; // 释放 Base 对象
basePtr = new Derived1(); // 现在指向 Derived1 对象的指针
checkType(basePtr); // 输出 "Derived1"
delete basePtr; // 释放 Derived1 对象
return 0;
}
2010
1.多项式类
设计一个多项式类Polynomial(包括构造函数、复制构造函数、析构函数、赋值函数、 实现两个多项式相加)
自己写的 这里运算符重载使用的是单目 注意vector的使用
//4、设计一个多项式类Polynomial(包括构造函数、复制构造函数、析构函数、赋值函数、 实现两个多项式相加)
#include<iostream>
#include<vector>
using namespace std;
class Polynomial
{
public:
Polynomial():n(0){}
//Polynomial():a(NULL),n(0){}
Polynomial(int arr[],int num){
n=num;
a.resize(n);
for(int i=0;i<n;i++)
{
a[i]=arr[i];
}
}
Polynomial(Polynomial& x)
{
n=x.n;
a=x.a;//注意vector的赋值操作不用遍历
}
~Polynomial()
{//vector不是new无需手动释放
}
int getnum(){return n;}
void set(int arr[],int num)
{
n=num;
a.resize(n);
for(int i=0;i<n;i++)
{
a[i]=arr[i];
cout<<a[i]<<" ";
}
cout<<endl;
}
/*跑不通
Polynomial operator+(const Polynomial b)
{
Polynomial c;
c.n=this->n>b.n?this->n:b.n;
a.resize(c.n);
for(int i=0;i<c.n;i++)
{
c.a[i]=this->a[i]+b.a[i];
}
return c;
}*/
// Polynomial operator+(Polynomial b)
// {
// if(this->n>b.n)
// {
// Polynomial c(*this);//复制拷贝函数
// c.n=this->n>b.n?this->n:b.n;
// for(int i=0;i<c.n;i++)
// {
// c.a[i]=this->a[i]+b.a[i];
// }
// return c;
// }
// else
// {
// Polynomial c(b);
// c.n=this->n>b.n?this->n:b.n;
// for(int i=0;i<c.n;i++)
// {
// c.a[i]=this->a[i]+b.a[i];
// }
// return c;
// }
// }
//(已修改)问题在于您在 if 和 else 语句块中分别创建了一个名为 c 的局部变量,但是这些变量是局部于各自的代码块,
//并且会在块结束时被销毁。因此,您在函数末尾返回的 c 并不是您在 if 或 else 块中修改的那个。
//最佳
Polynomial operator+(const Polynomial& b) const {
Polynomial c;
c.n = max(n, b.n);
c.a.resize(c.n, 0); // 初始化所有系数为0
for (int i = 0; i < n; i++) {
c.a[i] += a[i];
}
for (int i = 0; i < b.n; i++) {
c.a[i] += b.a[i];
}
return c;
}
void show()
{
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
}
private:
vector<int>a;
int n;
};
int main()
{
int arr1[]={1,2,3};
int arr2[]={5,6,-7,1};
Polynomial x1(arr1,3);
Polynomial x2(arr2,4);
x1.show();
x2.show();
Polynomial x3;
x3.set(arr2,4);
x3=x1+x2;
cout<<x3.getnum()<<endl;
x3.show();
}
参考他人
#include <vector>
#include <iostream>
using namespace std;
class Polynomial{
private:
vector<double> coef;
//通过向量coef依次存储多项式的系数
int size;
//多项式的项数
public:
Polynomial();
Polynomial(vector<double>, int);
Polynomial(const Polynomial&);
~Polynomial();
void setCoef( int, double);
double getCoef(int) const;
void print() const;
//通过友元函数重载的运算符返回值没有引用! ! !成员函数才有
friend Polynomial operator +( const Polynomial&, const Polynomial&);//两个参数
};
Polynomial:: Polynomial(){
size = 0;
}
Polynomial::Polynomial (vector<double> v,int n){
coef.assign(v. begin(),v.end());
size = n;
}
//拷贝构造函数
Polynomial::Polynomial (const Polynomial &p){
coef.assign(p.coef.begin(), p.coef.end());
size = p. size;
}
Polynomial::~Polynomial(){
coef.shrink_to_fit();
}
//C++11中新引入的释放vector的函数
void Polynomial::setCoef(int pos, double c){
coef[pos] = c;
}
double Polynomial::getCoef(int pos) const{
return coef[pos];
}
//打印多项式
void Polynomial::print() const{
int i=0;
//尝试用C++11的新特性:基于范围的for去遍历vector
for (auto const item:coef){
if (item != 0){
if(i==0)
cout << item;
else{
if(i==1)
cout << showpos << item << "x";
else
cout << showpos << item << "x^" << noshowpos <<i;
}
}
i++;
}
cout << endl;
}
//友元函数重载没有引用
Polynomial operator +(const Polynomial &p1, const Polynomial &p2){
if (p1.size > p2.size){
Polynomial p3(p1);
for (int i = 0;i < p2.size;i++)
p3. coef[i] = p1.coef[i] + p2.coef[i];
return p3;
}
else{
Polynomial p3(p2);
for (int i = 0;i < p1.size;i++)
p3. coef[i] = p1.coef[i] + p2.coef[i];
return p3;
}
}
int main(){
double a[5]={1,-2,3,-4.4,-3};
double b[7]={-3.6,1,-6,5,3,2.2,-7.6};
vector<double> v1(a,a+5);
//用指定数据初始化向量
vector<double> v2(b,b+7);
Polynomial p1(v1,5); //使用向量 v1初始化p1
Polynomial p2(v2,7);
//使用向量v2初始化p2
Polynomial p3(p2);
//调用拷贝构造函数
Polynomial p4;
//调用默认构造函数
p4=p1+p3;
//调用重载函数实现多项式相加
cout << "\np1 = ";
p1.print();
cout<<"\np2 = ";
p2.print();
cout<<"\np3 = ";
p3.print();
cout<<"\np4 = p1+p3 = ";
p4. print();
p4. setCoef(4, 444);
//改变多项式中某一项的系数
cout << "\nAfter setting\np4 = ";
p4. print( );
cout << endl ;
return 0;
}
2.字符串的解析
文件中有类似的一行行字符串“(010) (15012345678) |123| (430070)”,按以下格式输出:
“区号|电话号码|城市编号|邮编”
有三版 这里要熟练使用string 和一系列函数
自己写的出乱码
//字符串的解析
//文件中有类似的一行行字符串“(010) (15012345678) |123| (430070)”,按以下格式输出:
//“区号|电话号码|城市编号|邮编”
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
string s="(010)(15040438132)|123|(430070)";
string s1,s2,s3,s4;
int temp=0;
int n=s.size();
//cout<<n<<endl;
for(int i=0;i<n;i++)
{
if(s[i]=='(')
{
if(temp==0)
{
for(int j=i+1;s[j]!=')';j++)
{
s1+=s[j];
}
temp++;
}
else if(temp==1)
{
for(int j=i+1;s[j]!=')';j++)
{
s2+=s[j];
}
temp++;
}
else if(temp==2)
{
for(int j=i+1;s[j]!=')';j++)
{
s4+=s[j];
}
temp++;
}
}
else if(s[i]=='|')
{
for(int j=i+1;s[j]!='|';j++)
{
s3+=s[j];
}
}
}
cout<<s1<<'|'<<s2<<'|'<<s3<<'|'<<s4<<endl;
}
参考他人 假设已知长度 这里注意文件中行的提取用getline
//“区号|电话号码|城市编号|邮编”
//str.substr(第一位,字符串个数)
#include <iostream>
#include <string>
#include <cstring>
#include<fstream>
using namespace std;
int main(){
ifstream file("note.txt");
if(!file)
{
cerr<<"file cannot open"<<endl;
}
string str;
string num,tel,city,mail;
while(getline(file,str))//按行读取
{
num=str.substr(1,3);
tel=str.substr(6,11);
city=str.substr(19,3);
mail=str.substr(24,6);
cout<<num<<"|"<<tel<<"|"<<city<<"|"<<mail<<endl;
}
file.close();
}
参考他人 substr() find()各种函数调用 爽
//str.find("字符")找到字符所在位置 str.erase(去掉字符首个位置,去掉字符个数)
//“区号|电话号码|城市编号|邮编”
//str.substr(第一位,字符串个数)
#include <iostream>
#include <string>
#include <cstring>
#include<fstream>
using namespace std;
int main(){
ifstream file("note.txt");
if(!file)
{
cerr<<"file cannot open"<<endl;
}
string str;
string num,tel,city,mail;
while(getline(file,str))//按行读取
{
num=str.substr(str.find("(")+1,str.find(")")-str.find("(")-1);
str.erase(str.find("("),str.find(")")-str.find("(")+1);
tel=str.substr(str.find("(")+1,str.find(")")-str.find("(")-1);
str.erase(str.find("("),str.find(")")-str.find("(")+1);
mail=str.substr(str.find("(")+1,str.find(")")-str.find("(")-1);
str.erase(str.find("("),str.find(")")-str.find("(")+1);
city=str.substr(str.find("|")+1,str.size()-2);
cout<<num<<"|"<<tel<<"|"<<city<<"|"<<mail<<endl;
}
file.close();
}
3.十进制转二进制
这里用str前加来实现二进制输出 动态数组分配大小
#include<iostream>
#include<fstream>
#include<cstring>
#include<vector>
using namespace std;
// 使用std::string而不是char*来避免手动内存管理
string binary(int a) {
string str;
while (a > 0) {
str = (a % 2 == 1 ? '1' : '0') + str;
a /= 2;
}
return str;
}
int main() {
int n;
cin >> n;
// 使用vector来动态分配数组大小
vector<int> arr(n);
ofstream myfile("binary.txt", ios::app);
for (int i = 0; i < n; i++) {
cin >> arr[i];
string a = binary(arr[i]);
myfile << a << " ";
}
myfile.close();
return 0;
}
这里用reverse函数倒置字符串 注意头文件algorithm
下面while通过n--输入也挺巧妙
//2010_ 1:输入n个十进制数转换成二进制写到文件, n是随机得到
#include <iostream>
#include <cstring>
#include <fstream>
#include <algorithm> // 包含 std::reverse
using namespace std;
//10进制转2进制字符串的函数,没有考虑负数情况
string toBinary(int d){
string s;
if(d==0) return "0";
while (d>=1){
s += (d%2 > 0) ? "1":"0";
d = d/2;}
reverse(s.begin(), s.end());
//字符串逆置
return s;
}
int main(){
ofstream os("BinaryNumber.txt" );
if (!os) {
cerr << "File cannot be opened! \n" ;
exit( EXIT_FAILURE);
}
int n;
cout << "Enter the n:\n";
cin >> n;
int decimal;
while(n>0){
cout << "Please enter a decimal number:\n";
cin >> decimal;
os << toBinary(decimal) <<" ";
//写入文件
n--;
}
return 0;
}
3.汽车设计类与实现
Vehicle是基类,Car 类继承Vehicle类,包含类成员wheel 最后print的调用需要分清
继承+组合
//5、几个类(Vehicle类Car类Streetwheel 类Brake类)有着必然的联系,设计类与实现
//Vehicle是基类,Car 类继承Vehicle类。而Streetwheel类Brake类的对象又会作为Car类的成员,体现的是软件复用性。
#include<iostream>
#include<string>
using namespace std;
class Vehicle
{
public:
Vehicle(int a=0):speed(a)
{
}
~Vehicle(){
}
int getspeed()const{return speed;
}
private:
int speed;
};
class Wheel
{
private:
string wheelBrand;
public:
Wheel(string s=""):wheelBrand(s){}
string getbrand() const{return wheelBrand;}
void setwheel(string s){wheelBrand=s;}
};
class Car:public Vehicle
{
private:
string carbrand;
Wheel wheel;//成员对象是一个类
public:
Car(int s,string cBrand,string wBrand):Vehicle(s)
{
carbrand=cBrand;
wheel.setwheel(wBrand);
}
void print()
{
cout<<"Speed="<<getspeed()<<endl;//继承共有函数不用加类名称
//cout<<"Speed="<<speed<<endl;//公有继承私有对象 私有成员只能在其所在的类内部被访问,而不能从派生类或其他任何地方直接访问。
cout<<"Car brand ="<<carbrand<<endl;//类内直接调用私有成员
cout<<"Wheel brand ="<<wheel.getbrand()<<endl;//不是继承 不能通过对象访问私有成员 因此调用公有函数
}
};
int main()
{
Car mycar(200,"BMW","米其林");
mycar.print();
return 0;
}
4.图形设计类与实现
一个基类Shape,在基类的基础上继承写一个二维图形类,再继承写一个三维图形类,设计与实现
自己设计的 可以学一下构造函数(初始化,赋值)
//一个基类Shape,在基类的基础上继承写一个二维图形类,再继承写一个三维图形类,设计与实现
#include<iostream>
using namespace std;
class Shape
{
public:
Shape(int xx=0,int yy=0):x(xx),y(yy){}
~Shape(){}
int getx(){return x;}
int gety(){return y;}
private:
int x;
int y;
};
class Two:public Shape
{
public:
Two(int xx,int yy):Shape(xx,yy){}
~Two(){}
int getS(){return getx()*gety();}
};
class Three:public Shape
{
public:
Three(int xx=0,int yy=0,int hh=0):Shape(xx,yy),high(hh){}
~Three(){}
int getV(){return getx()*gety()*geth();}
int geth(){return high;}
private:
int high;
};
int main()
{
Two a(2,30);
Three b(5,2,4);
Three c;
cout<<a.getS()<<" "<<b.getV()<<" "<<c.getx()<<c.gety()<<c.geth();
}
参考
#include <string>
#include <iostream>
using namespace std;
//抽象类
class Shape{
private:
string color;
public:
Shape(string c):color(c){ }
virtual int calculate() const = 0;
//纯虚函数
string getColor() const{
return color;
}
};
class _2D_Shape:public Shape{//数字不能做名称开头
private:
int length;
int width;
public:
_2D_Shape(string c,int l,int w):Shape(c){
length = l;
width = w;
}
int getLength() const {return length;}
int getWidth() const {return width;}
//这里仍要声明为virtual,以便3D_Shape 继承时再次重写calculate()函数
virtual int calculate() const override{return getWidth()*getLength();}
};
class _3D_Shape : public _2D_Shape{
private:
int height;
public:
_3D_Shape(string c,int l,int w,int h):_2D_Shape(c,l,w){
height = h;}
int getHeight() const {return height;}
int calculate()const override{
return _2D_Shape::calculate()*height;
}
};
int main(){
Shape * shapePtr;//定义一个虚基类指针
_2D_Shape shape_2d("Green", 10,5);
_3D_Shape shape_3d("Red", 4, 5, 7);
cout << "The area of the 2D shape is: " << shape_2d.calculate()<< endl;
cout << "The volume of the 3D shape is: " << shape_3d.calculate()<< endl;
cout << "The 2D area of the 3D shape is: "<< shape_3d._2D_Shape::calculate()<< endl;//3d中调用对象函数
/***** *********多态性***************/
shapePtr = &shape_2d;
cout << "The shapePtr calls calculate: " << shapePtr->calculate()<< endl;
shapePtr = &shape_3d;
cout << "The shapePtr calls calculate: " << shapePtr->calculate()<< endl ;
/************************************/
return 0;
}
2011
1、编写一个程序,利用下面的公式计算e^x的值, 精确到10^-10
![](https://i-blog.csdnimg.cn/blog_migrate/09c04707b09ad3a006fe080b4e53e32c.png)
- 浮点数精确值
fabs(temp) >= 1e-10
是一个数学表达式,通常用在编程中,特别是在处理浮点数比较时。这个表达式用于判断一个浮点数
temp
的绝对值是否大于或等于1e-10(10^-10)
。在科学记数法中,a × 10^n 表示的是 a乘以10的n次方。
所以,10e-10 实际上是 10 × 10^-10,而 1e-10 是 1 × 10^-10。
fabs
是一个函数,用于计算浮点数的绝对值。cmath头文件temp
是计算其绝对值的浮点数,这里取项数,因为每一项都在不断减少1e-10
是一个科学记数法表示的浮点数,等于0.0000000001
- 如何输出精确到小数点后n位
printf("%.nf",number);
//n表示精确位数
printf("PI = %.6f\n", 3.1415966);
//输出这个数字并精确到其小数点后共6位数字来do输出!
#include<iomanip>//添加头文件
①cout<<setprecision(n)<<fixed<<数字<<endl;!
②cout<<setprecision(n)<<数字<<endl;
double PI = 3.141596;
cout << setprecision(7) << fixed << PI << endl;
//输出这个数字并精确到其小数点后共7位数字来do输出!fixed
fixed
确保浮点数总是以小数点形式输出,并且小数点后的位数可以通过setprecision
来控制。不使用fixed
,浮点数可能会以科学计数法形式输出。
原文链接:https://blog.csdn.net/weixin_44980842/article/details/120694082
- x的n次方
#include<cmath>
pow(x, y)
//函数返回x
的y
次方。
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
double x;
cin>>x;
double result=1;
double n=1;//统一类型都是double
double k=1;//阶乘
double temp;//每一项结果用于判断是否在精确度
do{
temp = pow(x,n)/k;
result+=temp;
n++;
k=k*n;
}while(fabs(temp)>1e-10);
cout<<"e^"<<x<<"="<<fixed<<setprecision(10)<<result<<endl;
return 0;
}
- do-while和while区别
while循环执行时只有当满足条件时才会进入循环,进入循环后,执行完循环体内全部语句直到条件不满足时,再跳出循环。
do-while循环将先运行一次,在经过第一次do循环后,执行完一次后检查条件表达式的值是否成立,其值为不成立时才会退出循环。
while循环是先判断后执行,如果判断条件不成立可以不执行中间循环体。
do-while循环是先执行后判断,执行次数至少为一次,执行一次后判断条件是否成立,如果不成立跳出循环,成立则继续运行循环体
原文链接:https://blog.csdn.net/heishuiloveyou/article/details/127953503
试用 while重写级数 包含符号变化 需要初始化temp的值
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
double x;
cin>>x;
double result=1;
double n=1;//统一类型都是double
double k=1;//阶乘
double temp=1;//每一项结果用于判断是否在精确度
double flag=1;//实现符号改变
while(fabs(temp)>1e-10){
temp = pow(x,n)/k;
result+=flag*temp;
flag=-flag;
n++;
k=k*n;
}
cout<<"e^"<<x<<"="<<fixed<<setprecision(10)<<result<<endl;
return 0;
}
2、编写一个程序,利用下面的公式计算pi的值,要求小数点后的位数为计算机可表达的最大范围。
![](https://i-blog.csdnimg.cn/blog_migrate/8c7c679e0ca06498c0c75b102b75af32.png)
1e-8还能很快计算出来 1e-10就要等一阵了
计算机表示的最大范围没研究明白 感觉跟计算机系统有关了
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main()
{
double pi=1;
double n=1;
double flag=1;
double temp=1;
do{
n=n+2;
temp=1/n;
flag=-flag;
pi+=flag*temp;
}while(fabs(temp)>1e-10);
cout<<"pi= "<<pi*4<<fixed<<setprecision(10)<<endl;
return 0;
}
3.编写一个递归函数模板,从一个数组中找出最小值,并返回该值的数组元素下标。
自己写的 举例然后思考递归过程 n从大到小再从小到达跳出
//3、编写一个递归函数模板,从一个数组中找出最小值,并返回该值的数组元素下标。
#include<iostream>
using namespace std;
int position(int *arr,int n,int min,int min_index)
{
if(n==0) return min_index;
if(arr[n-1]<min)
{
min=arr[n-1];
min_index=n-1;
}
position(arr,n-1,min,min_index);
}
int main()
{
int arr[]={2,3,0,5,7};
int min=position(arrn,5,arr[0],0);
cout<<min<<endl;
}
参考
#include<iostream>
using namespace std;
template <typename T>
int position(T a[],int start, int end)
{
static int min=start;
if(a[start]<a[min])
{
min=start;
}
if(start<end)
{
return position(a,start+1,end);
}
return min;
}
int main()
{
int arr[]={2,3,0,5,7};
int min=position(arr,0,sizeof(arr)/sizeof(arr[0])-1);
cout<<min<<endl;
}
4.字符串排序 插入排序 选择排序
#include<iostream>
#include<string>
using namespace std;
template <typename T>
void Sort1(T a[],int n){//插入排序
int i,j;
for(int i=1;i<n;i++)
{
if(a[i]<a[i-1]) {
T temp=a[i];
for(j=i-1;a[j]>temp&&j>=0;j--)//不能重定义int j 不然无法运行
{
a[j+1]=a[j];
}
a[j+1]=temp;
}
}
}
template <typename T>
void Sort2(T a[],int n){//选择排序
for(int i=0;i<n-1;i++)
{
int min=i;
for(int j=i+1;j<n;j++)
{
if(a[j]<a[min]) min=j;
}
if(min!=i)
{
T temp=a[min];
a[min]=a[i];
a[i]=temp;
}
}
}
int main(){
string s1[7] = {"abcd", "e", "abc", "abd", "bcd", "bf" , "bbzzzz"};
string s2[6] = {"eabc", "af", "ez", "fee" , "fdee", "aeee"};
int arr[6]={65,8,5,3,2,1};
Sort1(s1, 7);
Sort1(arr,6);
//调用插入排序(从小到大)
Sort2(s2, 6);
//调用选择排序(从小到大)
cout << "s1 sorted by SortOne... \n";
for (string item : s1)
cout << item << " ";
cout << "\n\ns2 sorted by SortTwo... \n";
for (string item : s2)
cout << item << " ";
cout << "\n\narr sorted by SortOne... \n";
for (int item : arr)
cout << item << " ";
cout << endl;
return 0;
}
5、对于一个数组Array类的chess对象
对于一个数组Array类的chess对象通过调用运算符重载函数(),可实现chess(row, column)代替chess [row][column],请完成:
(1)、 Array类的基本定义,包括构造函数、析构函数、拷贝构造函数和基本数据成员;
(2)、运算符重载函数()的定义。
这道题的核心思想是在自定义数组类中,通过一维指针ptr存储自定义二维数组的所有元素,当调用构造函数或拷贝构造函数时需要为指针ptr动态申请存储空间,即:ptr = new int[rows * columns];
当然,调用析构函数时也要将申请的空间全部释放。.
为了使这个自定义数组真正具有可行性,添加了两个通过友元函数重载的<<符号与>>符号,以便输入或输出数组。
Array.h
#ifndef ARRAY_H
#define ARRAY_H
//宏名称通常大写不包含.
#include<iostream>
using namespace std;
class Array
{ friend istream &operator>>(istream &input, Array &a);
friend ostream &operator<<(ostream &out,const Array &a);
private:
int row;
int column;
int* arr;
public:
Array():row(0),column(0){}
Array(int** a,int n,int m);
Array(int,int);
Array(Array &a);
~Array();
int &operator()(int a,int b)const;
};
#endif /*Array_h*/
Array.cpp 不知道为什么运行不了
这里重载运算符一定要多看
#include "Array.h"
Array::Array(int** a,const int n,const int m)//a是二维数组指针
{
row=n;column=m;
arr=new int[n*m];//初始化一维数组 以二维数组方式存取
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
arr[i*n+j]=a[i][j];
}
}
}
Array::Array(int n,int m)
{
row=n;column=m;
arr=new int[n*m];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
arr[i*n+j]=0;
}
}
}
Array::Array(Array &a){
row=a.row;column=a.column;
arr=new int[row*column];
for(int i=0;i<row;i++)
{
for(int j=0;j<column;j++)
{
arr[i*row+j]=a.arr[i*row+j];
}
}
}
Array::~Array(){
delete[] arr;
}
int &Array::operator()(int a,int b)const
{
return arr[a*column+b];//没有友元能用私有对象吗 成员函数可以访问类体内的任何成员,包括私有成员
//成员函数可以理解为私有对象和类外调用的接口 主函数就访问不了私有对象 但可以通过调用成员函数访问
}
istream &operator>>(istream &input, Array &a){//输入不能const 必须引用operator
for(int i=0;i<a.row;i++)
{
for(int j=0;j<a.column;j++)
{
input>>a.arr[i*a.column+j];
}
}
return input;
}
ostream &operator<<(ostream &out,const Array &a){//输出不改变必须const
for(int i=0;i<a.row;i++)
{
for(int j=0;j<a.column;j++)
{
out<<a.arr[i*a.column+j]<<" ";
}
cout<<endl;
}
return out;
}
main.cpp
#include<Array.h>
#include<iostream>
using namespace std;
int main()
{
int arr1[2][3]={1,2,3,4,5,6}
Array a1(arr1,2,3);
cout<<"a1:\n"<<a1<<endl;
Array a2(3,2);
cin>>a2;
cout<<"a2:\n"<<a2<<endl;
cout<<a2(2,1)<<endl;
}
6、定义一个具有多态性的基类Shape
定义一个具有多态性的基类Shape, 派生出三个类:Circle(坐标点和半径),矩形Rec类(两点不同坐标),三角形Tri类(三个不同坐标),每个类中至少有一个计算面积的函数。编写程序,从文件file.txt中读取数据来创建各类的对象,并放在Shape指针向量中,最后循环处理每个对象并输出面积。假设file.txt中的数据如下(加了两行便于测试) :
C:123,5, 40;T:1,2,32,50,60,3;R:6,8,8,100
C:2.2,1.1,3;T:1,1,3,1,2,2;R:1.3,1.9,3.3,2.9
C:100,0.01,1.2;T:1,1.1,4,1.1,1,5.1;R:0,0,-2,-2
最后文件输入极其复杂 没成功 学习语法吧
/*6、定义一个具有多态性的基类Shape定义一个具有多态性的基类Shape, 派生出三个类:圆Circle(坐标点和半径),矩
形Rec类(两点不同坐标),三角形Tri类(三个不同坐标),每个类中至少有一个计算面积的函数。编写程序,从文件file.txt中读取数据来创建各类的对象,
并放在Shape指针向量中,最后循环处理每个对象并输出面积。假设file.txt中的数据如下(加了两行便于测试) :
C:123,5, 40;T:1,2,32,50,60,3;R:6,8,8,100
C:2.2,1.1,3;T:1,1,3,1,2,2;R:1.3,1.9,3.3,2.9
C:100,0.01,1.2;T:1,1.1,4,1.1,1,5.1;R:0,0,-2,-2
*/
#define PI 3.14
#include<iostream>
#include<cmath>
#include<fstream>
#include<string>
using namespace std;
class Shape
{
public:
virtual double getS() =0;
virtual ~Shape() {}
};
class Circle:public Shape
{
private:
double x;
double y;
double r;
public:
Circle(double x, double y, double r) : x(x), y(y), r(r) {}
double getS()
{
return PI*r*r;
}
};
class Rec:public Shape
{
private:
double x1;
double y1;
double x2;
double y2;
public:
Rec(double x1, double y1, double x2, double y2) : x1(x1), y1(y1), x2(x2), y2(y2) {}
double getS()
{
return abs(x2-x1)*abs(y2-y1);
}
};
class Tri:public Shape
{
private:
double x1;
double y1;
double x2;
double y2;
double x3;
double y3;
public:
Tri(double x1, double y1, double x2, double y2, double x3, double y3)
: x1(x1), y1(y1), x2(x2), y2(y2), x3(x3), y3(y3) {}
double getS()
{
return 0.5*abs(x1*y2+x2*y3+x3*y1-x1*y3-x2*y1-x3*y2);
}
};
void findcircle(string &s,Shape *str);
void findtri(string &s,Shape *str);
void findrec(string &s,Shape *str);
int main()
{
ifstream file("data.txt");
if(!file)
{
cout<<"cannot open"<<endl;
}
string str;
Shape* ptr=NULL;
while(getline(file,str))
{
findcircle(str,ptr);
findtri(str,ptr);
findrec(str,ptr);
}
file.close();
return 0;
}
void findcircle(string &s,Shape *str){
double a,b,c;
a=stod(s.substr(s.find(":")+1,s.find(",")-s.find(":")-1));//stod字符串转化为double
s.erase(0,s.find(",")+1);
b=stod(s.substr(0,s.find(",")));
s.erase(0,s.find(",")+1);
c=stod(s.substr(0,s.find(";")));
s.erase(0,s.find(";")+1);
Circle m(a,b,c);
str=&m;
cout<<str->getS()<<endl;
}
void findtri(string &s,Shape *str){
double a,b,c,d,e,f;
a=stod(s.substr(s.find(":")+1,s.find(",")-s.find(":")-1));//stod字符串转化为double
s.erase(0,s.find(",")+1);
b=stod(s.substr(0,s.find(",")));
s.erase(0,s.find(",")+1);
c=stod(s.substr(0,s.find(";")));
s.erase(0,s.find(";")+1);
d=stod(s.substr(0,s.find(";")));
s.erase(0,s.find(";")+1);
e=stod(s.substr(0,s.find(";")));
s.erase(0,s.find(";")+1);
f=stod(s.substr(0,s.find(";")));
s.erase(0,s.find(";")+1);
Tri m(a,b,c,d,e,f);
str=&m;
cout<<str->getS()<<endl;
}
void findrec(string &s,Shape *str){
double a,b,c,d;
a=stod(s.substr(s.find(":")+1,s.find(",")-s.find(":")-1));//stod字符串转化为double
s.erase(0,s.find(",")+1);
b=stod(s.substr(0,s.find(",")));
s.erase(0,s.find(",")+1);
c=stod(s.substr(0,s.find(";")));
s.erase(0,s.find(";")+1);
d=stod(s.substr(0,s.find(";")));
Rec m(a,b,c,d);
str=&m;
cout<<str->getS()<<endl;
}