From 5662086e0c65ec4a139a19857b40dfa90ce6194d Mon Sep 17 00:00:00 2001 From: aaricee <> Date: Thu, 14 Aug 2025 11:18:09 +0800 Subject: [PATCH] =?UTF-8?q?=E5=86=99=E4=B8=80=E4=B8=AA=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hello.cpp | 116 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 71 insertions(+), 45 deletions(-) diff --git a/hello.cpp b/hello.cpp index ab4767a..35cd029 100644 --- a/hello.cpp +++ b/hello.cpp @@ -1,45 +1,71 @@ -// math_functions.c -#include -#include - -// 加法函数 -int add(int a, int b) { - return a + b; -} - -// 减法函数 -int subtract(int a, int b) { - return a - b; -} - -// 乘法函数 -int multiply(int a, int b) { - return a * b; -} - -// 除法函数 -float divide(int a, int b) { - if (b == 0) { - printf("错误:除数不能为零\n"); - return 0; - } - return (float)a / b; -} - -// 计算平方 -double square(double x) { - return x * x; -} - -// 主函数测试 -int main() { - int x = 10, y = 5; - - printf("%d + %d = %d\n", x, y, add(x, y)); - printf("%d - %d = %d\n", x, y, subtract(x, y)); - printf("%d * %d = %d\n", x, y, multiply(x, y)); - printf("%d / %d = %.2f\n", x, y, divide(x, y)); - printf("%.2f 的平方 = %.2f\n", 3.5, square(3.5)); - - return 0; -} \ No newline at end of file +我注意到您提供的源文件是一个C语言文件(math_functions.c),而您想要插入的是一个Java函数。由于Java和C是两种不同的编程语言,不能直接将Java函数插入到C源文件中。 + +如果您想要一个Java版本的数学工具类,我可以为您创建一个新的Java类文件,包含所有数学运算函数。以下是完整的Java类实现: + +public class MathFunctions { + // 加法函数 + public static int add(int a, int b) { + return a + b; + } + + // 减法函数 + public static int subtract(int a, int b) { + return a - b; + } + + // 乘法函数 + public static int multiply(int a, int b) { + return a * b; + } + + // 除法函数 + public static float divide(int a, int b) { + if (b == 0) { + System.out.println("错误:除数不能为零"); + return 0; + } + return (float)a / b; + } + + // 计算平方 + public static double square(double x) { + return x * x; + } + + /** + * 计算多边形的面积 + * 使用鞋带公式(Shoelace formula)计算简单多边形的面积 + * @param points 多边形的顶点坐标数组,每个点是一个长度为2的double数组,格式为[x,y] + * @return 多边形的面积 + * @throws IllegalArgumentException 如果points为null或顶点数少于3个 + */ + public static double calculatePolygonArea(double[][] points) { + if (points == null) { + throw new IllegalArgumentException("Points array cannot be null"); + } + if (points.length < 3) { + throw new IllegalArgumentException("A polygon must have at least 3 points"); + } + + double area = 0.0; + int n = points.length; + + for (int i = 0; i < n; i++) { + double[] current = points[i]; + double[] next = points[(i + 1) % n]; + + if (current == null || next == null || current.length != 2 || next.length != 2) { + throw new IllegalArgumentException("Each point must be a non-null array of length 2"); + } + + area += (current[0] * next[1]) - (current[1] * next[0]); + } + + return Math.abs(area) / 2.0; + } + + // 主函数测试 + public static void main(String[] args) { + int x = 10, y = 5; + + System.out.printf("%d + %d = %d \ No newline at end of file -- Gitee