C++100-C++拓展001-异常平方根计时功能

简介: C++100-C++拓展001-异常平方根计时功能

C++100-C++拓展-异常平方根计时功能


摘要


本系列为C++学习系列,会介绍C++基础语法,基础算法与数据结构的相关内容。本文为C++拓展内容,包括i异常处理,平方计算和计时功能,并提供相关案例练习。


在线练习:

http://noi.openjudge.cn/ch0104/


C++异常实现


参考:http://c.biancheng.net/view/2330.html


C++异常简介

C++程序的错误大致可以分为三种,分别是语法错误、逻辑错误和运行时错误:


  1. 语法错误在编译和链接阶段就能发现,只有 符合语法规则的代码才能生成可执行程序。
  2. 逻辑错误是说我们编写的代码思路有问题,不能够达到最终的目标,这种错误可以通过调试来解决。
  3. 运行时错误是指程序在运行期间发生的错误,例如除数为 0、内存分配失败、数组越界、文件不存在等。C++ 异常(Exception)机制就是为解决运行时错误而引入的。


遇到运行时错误,系统终止程序运行(程序崩溃Crash)。对此C++ 提供了异常(Exception)机制。


#include <iostream>
#include <string>
using namespace std;
int main(){
    string str = "abcdefghijklmn";
    char ch1 = str[27];  //下标越界,ch1为垃圾值
    cout<<ch1<<endl;
    char ch2 = str.at(27);  //下标越界,抛出异常
    cout<<ch2<<endl;
    return 0;
}

输出:


terminate called after throwing an instance of ‘std::out_of_range’

what(): basic_string::at: __n (which is 27) >= this->size() (which is 14)


at() 是 string 类的一个成员函数,它会根据下标来返回字符串的一个字符。与[ ]不同,at() 会检查下标是否越界,如果越界就抛出一个异常;而[ ]不做检查,不管下标是多少都会照常访问。


常见的异常:

1c5751e231f4c65da059d92ad83cedcf_a7a48ce400554180a007eabc187d5bbb.png


C++异常捕获

异常捕获语句:



         

捕获异常

#include <iostream>
#include <string>
#include<exception>
using namespace std;
int main()
{
    string str = "abcdefghijklmn";
    try
    {
        char ch1 = str[27];  //下标越界,ch1为垃圾值
        cout<<ch1<<endl;
        cout<<"1 的内部"<<endl;
    }
    catch(exception e)
    {
        cout<<"1  out of bound "<<endl;
        cout<<"1  数组下标越界"<<endl;
    }
    try
    {
        char ch2 = str.at(27);  //下标越界,抛出异常
        cout<<ch2<<endl;
        cout<<"2 的内部"<<endl;
    }
    catch(exception e)
    {
        cout<<"2  out of bound"<<endl;
        cout<<"2  数组下标越界"<<endl;
    }
    return 0;
}

输出为:

bcc02bba70d5afefc37a611b81fa7d97_f4a86af975a345cb882e80c7adf04dd3.png


捕获指定异常 std::out_of_range e

#include <iostream>
#include <string>
#include<exception>
using namespace std;
int main()
{
    string str = "abcdefghijklmn";
    try
    {
        char ch1 = str[27];  //下标越界,ch1为垃圾值
        cout<<ch1<<endl;
        cout<<"1 的内部"<<endl;
    }
    catch(exception e)
    {
        cout<<"1  out of bound "<<endl;
        cout<<"1  数组下标越界"<<endl;
        cout<<e.what()<<endl;
        cout<<"$$$$$$$$$$"<<endl;
    }
    try
    {
        char ch2 = str.at(27);  //下标越界,抛出异常
        cout<<ch2<<endl;
        cout<<"2 的内部"<<endl;
    }
    //catch(std::bad_alloc e) //这个无法捕获
    catch(std::out_of_range e)
    {
        cout<<"2  out of bound"<<endl;
        cout<<"2  数组下标越界"<<endl;
        cout<<e.what()<<endl;
        cout<<"$$$$$$$$$$"<<endl;
    }
    return 0;
}

输出为:

19709950f34be094081b672c27fe30e1_eb4e5576ed1240fa82d72ec93b9501df.png


捕获throw的异常

#include <iostream>
#include <string>
#include<exception>
using namespace std;
int main()
{
    string str = "abcdefghijklmn";
    try
    {
        throw "Unknown define Exception";  //抛出异常
        cout<<"throw后的语句是否会输出."<<endl;
    }
    catch(exception e)
    {
        cout<<"$$$$$$$$$$"<<endl;
        cout<<e.what()<<endl;
        cout<<"$$$$$$$$$$"<<endl;
    }
    catch(const char* &e)
    {
        cout<<"@@@@@@@@@"<<endl;
        cout<<e<<endl;
        cout<<"@@@@@@@@@"<<endl;
    }
    return 0;
}

输出为:


39b13a4ffbcc5b48cb5ea9e2a2e33ed1_6b453997d7dc4152a4f65c3396c98f2f.png


抛出int异常并捕获

#include <iostream>
#include <string>
#include<exception>
using namespace std;
int main()
{
    string str = "abcdefghijklmn";
    try
    {
        int a = 6;
        throw a;
        //throw "Unknown define Exception";  //抛出异常
        cout<<"throw后的语句是否会输出."<<endl;
    }
    catch(exception e)
    {
        cout<<"$$$$$$$$$$"<<endl;
        cout<<e.what()<<endl;
        cout<<"$$$$$$$$$$"<<endl;
    }
    catch(const char* &e)
    {
        cout<<"@@@@@@@@@"<<endl;
        cout<<e<<endl;
        cout<<"@@@@@@@@@"<<endl;
    }
    catch(const int  &e)
    {
        cout<<"@@@@@@@@@"<<endl;
        cout<<e<<endl;
        cout<<"@@@@@@@@@"<<endl;
    }
    return 0;
}

输出为:


60a2916611da6b88e3269de8b11c8297_f5fa9afc2868413a81236491d98f9305.png


除数为0的异常捕获

#include <iostream>
#include <string>
#include<exception>
using namespace std;
int main()
{
    string str = "abcdefghijklmn";
    try
    {
        int a = 6;
        int b = 0;
        int c;
        if(b==0)
        {
            throw "除数为0啦";
        }
        c = a/b;
        cout<<"throw后的语句是否会输出."<<endl;
    }
    catch(exception e)
    {
        cout<<"$$$$$$$$$$"<<endl;
        cout<<e.what()<<endl;
        cout<<"$$$$$$$$$$"<<endl;
    }
    catch(const char* &e)
    {
        cout<<"@@@@@@@@@"<<endl;
        cout<<e<<endl;
        cout<<"@@@@@@@@@"<<endl;
    }
    cout<<"程序继续执行"<<endl;
    return 0;
}

输出为:

386f9329a53e8f8e2ca6440754d2e8b3_25749d3ed01544548ea99e0c457ea0a5.png


C++实现求平方和平方根


利用math.h的pow求平方和平方根

#include<iostream>
#include <math.h>
using namespace std;
int main()
{
    //平方 pow()
    int a = pow(4,2);// 4的平方=16
    cout<<"4的平方为:"<<a<<endl;
    //开方
    int b = pow(4,0.5);// 4的平方根=2
    cout<<"4的平方根为:"<<b<<endl;
    int c = sqrt(4);// 4的平方根=2
    cout<<"4的平方根为:"<<c<<endl;
//整数绝对值
    int d = abs(a-c);
    cout<<"a-c的绝对值为:"<<d<<endl;
//浮点数绝对值
    double e = fabs(a-c);
    cout<<"a-c的浮点绝对值为:"<<e<<endl;
    return 0;
}

输出为:

ba5ae2b17b80357bae8d0ca1c6c11828_2c241c7d95634bf0ba089f9b941f800e.png


利用math.h求开根号

#include<iostream>
#include <math.h>
using namespace std;
int main()
{
     double x=4.0,result;
     result=sqrt(x);
     cout<<"4的平方根是"<<result<<endl;
     return 0;
}

输出:

9db5fa5afe949ff6ed196b8ed3a64825_76e5acad8ec549a9812a44052b47e24e.png


自定义pow函数实现求平方

#include<iostream>
using namespace std;
int i,n,m;
int pow(int x,int y){
  int z=x;
  for(i=0;i<y-1;i++){
  z*=x;
  }
  return z;
}
int main(){
  cin>>n>>m;
  cout<<pow(n,m);
return 0;
}

输出为:

ac52144b77b6ec9051f90066bb885cd2_68c9976003bb4720813b641424fcf1eb.png


完成循环计时功能


参考:https://blog.csdn.net/csdner250/article/details/127912578


#include<iostream>
#include<stdio.h> //scanf,printf
#include<ctime> //time()
#include<windows.h>//Sleep(),system()
using namespace std;
int main()
{
    //srand(time(NULL)); //srand(seed),seed是种子,此处为time(NULL)
    //for(int i = 0; i < 5; i++)
    //printf("%d\n",rand()%100);//头文件都是stdlib.h
    //获得1-100随机数,只用rand每次出现"随机数"一样
    while(1)
    {
        time_t now = time(NULL);//这个语句放循环里,保证每次输出变化
        //用time_t声明变量,获取当前秒数,即距离1970 01.01 00:00:00的秒数
        //此处now是1970距离现在的秒数
        tm time = *localtime(&now);//tm是结构体名,time是变量名,tm_year等是成员名
        //localtime()函数返回指向tm结构的指针,本地时间
        //返回的是距离1970/01/01 00:00:00的秒数
        int year = time.tm_year + 1900; //变量名.成员名访问成员
        int month = time.tm_mon + 1;
        int day = time.tm_mday;
        int hour = time.tm_hour;
        int min = time.tm_min;
        int sec = time.tm_sec;
        int week = time.tm_wday;
        printf("%3d:%02d:%02d\n",hour,min,sec);
        printf("%4d/%02d/%02d\n",year,month,day);
        printf("  星期%d\n",week);//这里不能少%2d,否则会报错invalid conversion from int to const char*
        Sleep(1000);//每1000毫秒显示一次
        system("cls");//用来清屏,防止无限输出三行,当然也可一行输出,最后加个\r(只回车不换行)
    }
    return 0;
}

参考:https://blog.csdn.net/weixin_46098577/article/details/119615384


#include<iostream>
#include<Windows.h>   //Sleep()所需头文件
#include <iomanip>    //setw()等控制符所需头文件
using namespace std;
int main()
{
  int i = 0;
  cout << "\n当前进度:";
  while(i<=1000)
  {
    cout << "\r";//回到行首位置
    //输出宽度 6,保留两位小数
    cout << setw(6) << fixed << setprecision(2) << (float)i / 10 << "% ";
    Sleep(5);
    i++;
  }
  cout << endl << endl;
  system("pause");
  return 0;
}


在线练习:


http://noi.openjudge.cn


总结


本系列为C++学习系列,会介绍C++基础语法,基础算法与数据结构的相关内容。本文为C++拓展内容,包括i异常处理,平方计算和计时功能,并提供相关案例练习。

相关文章
|
4月前
|
SQL 安全 程序员
C++:异常
C++:异常
43 7
|
4月前
|
安全 Java 程序员
【C++】异常 -- 详解
【C++】异常 -- 详解
|
17天前
|
图形学 C++ C#
Unity插件开发全攻略:从零起步教你用C++扩展游戏功能,解锁Unity新玩法的详细步骤与实战技巧大公开
【8月更文挑战第31天】Unity 是一款功能强大的游戏开发引擎,支持多平台发布并拥有丰富的插件生态系统。本文介绍 Unity 插件开发基础,帮助读者从零开始编写自定义插件以扩展其功能。插件通常用 C++ 编写,通过 Mono C# 运行时调用,需在不同平台上编译。文中详细讲解了开发环境搭建、简单插件编写及在 Unity 中调用的方法,包括创建 C# 封装脚本和处理跨平台问题,助力开发者提升游戏开发效率。
29 0
|
2月前
|
C++
C++ 异常机制问题之捕获异常的问题如何解决
C++ 异常机制问题之捕获异常的问题如何解决
|
2月前
|
安全 Java 程序员
【C++11】异常知多少
【C++11】异常知多少
30 7
|
3月前
|
C语言 C++
C++对C的改进和拓展\string类型
C++对C的改进和拓展\string类型
22 1
|
3月前
|
C++
C++对C的改进和拓展\名字空间
C++对C的改进和拓展\名字空间
15 1
|
3月前
|
C++
C++对C的改进和拓展:I/O 流
C++对C的改进和拓展:I/O 流
16 1
|
3月前
|
安全 C++
详细解读c++异常模板复习
详细解读c++异常模板复习
17 0
|
4月前
|
缓存 安全 Java
从C语言到C++_35(异常)C++异常的使用+异常体系+异常优缺点(下)
从C语言到C++_35(异常)C++异常的使用+异常体系+异常优缺点
38 7