软件园学生在线

  • {{ item.name }}
  • 2023试用期

登录与注册

如何判断整型数值溢出

  • 高 靖原
  • 2022-12-24
  • 0

如何判断整型数值溢出


一. 基础知识回顾

·REST API API是一种应用程序接口,通俗来讲,就是用户可以通过API实现对应用程序中某个数据的操作如修改或者调用,而REST API则是一种通过http来调用的API,可以理解为一种URL,即一个网址

·GET请求 GET就英文翻译的意思的得到,当你向一个API发送GET请求时,你会得到相应的信息,例如,当你向baidu.com发送GET请求时,你就会得到百度的源代码,进而进行各种操作

·POST请求 数据会包含在请求体中,可能会导致新的资源的创建和/或已有资源的修改

·Spring Boot 在培训的时候跟着zygg用Spring Boot做了一个比较简单的a+b的API,让我们简单了解了操作步骤以及注解的作用

二.产品功能

·整数值的加法运算,具体操作方法为在浏览器中输入localhost:8080/add?a=num1&b=num2 (num1和num2代表两个具体的整数)

·整数值的减法功能,具体操作方法为在浏览器中输入localhost:8080/subtract?a=num1&b=num2

·整数值的乘法功能,具体操作方法为在浏览器中输入localhost:8080/multiply?a=num1&b=num2

·整数值的除法功能,具体操作方法为在浏览器中输入localhost:8080/divide?a=num1&b=num2

三. 判断整型数值溢出

1.^和&运算符的含义

^(异或运算符)

^是针对二进制的二目运算符,运算规则:两个二进制数值如果在同一位上相同,则该结果中该位为0,否则为1,比如1101^0010 = 1001

&(与运算符)

&是针对二进制的二目运算符。需要注意的是&&是java中判断条件之间表示“和”的标识符,&是一个二目运算符,两个二进制数值如果在同一位上都是1,则结果中该位为1,否则为0,比如1011 & 0110 = 0010

2.原理

只有两个正数或两个负数相加结果才会溢出,而且溢出后的结果一定与原值相反

3.具体方法

当结果溢出时,r与a,b的符号相反,((a^r)&(b^r))的结果为1,所以会小于0,因此结果溢出;减法的原理与加法相似;乘法的原理先把int型变量转换为long型,再进行运算,之后再转换为int型,与转换前进行比较,如果值不想同,则说明结果溢出;除法是不会出现溢出的情况的,所以不用考虑

int r= a + b;  
if(((a^r)&(b^r))<0){
    throw new ArithmeticException("integer overflow");
}
return r;
int r= a - b;
if(((a^b)&(a^r))<0){
    throw new ArithmeticException("integer overflow");
}
return r;

四.代码

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MainController {

@GetMapping("/add")
public static int add(@RequestParam int a, @RequestParam int b){
    int r = a + b;
    if(((a^r)&(b^r))<0){
    throw new ArithmeticException("integer overflow");
}
return r;
}

@GetMapping("/subtract")
public static int subtract(@RequestParam int a, @RequestParam int b){
    int r= a - b;
    if(((a^b)&(a^r))<0){
    throw new ArithmeticException("integer overflow");
}
return r;
}

@GetMapping("/multiply")
public int multiply(@RequestParam int a, @RequestParam int b){
    long r = (long)a * (long)b;
    if((int)r!=r){
    throw new ArithmeticException("integer overflow");
}
return (int)r;
}

@GetMapping("/divide")
public double divide(@RequestParam double a, @RequestParam double b){
    return a / b;
}
}
高 靖原
高 靖原
© 2025 软件园学生在线
Theme by Wing