From a9384c94421a6e36315fe0deebe3583d10adfa18 Mon Sep 17 00:00:00 2001 From: aaricee <> Date: Thu, 14 Aug 2025 11:34:12 +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 | 113 ++++++++++++++++++++++++++++++++---------------------- 1 file changed, 68 insertions(+), 45 deletions(-) diff --git a/hello.cpp b/hello.cpp index ab4767a..dc00df8 100644 --- a/hello.cpp +++ b/hello.cpp @@ -1,45 +1,68 @@ -// 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中插入函数。由于源文件是C语言而非Java,我无法直接将Java方法插入到C源文件中。 + +如果您想要一个Java版本的数学工具类,我可以为您提供一个完整的Java类文件,其中包含原始C文件中的数学函数和新的多边形面积计算方法。以下是完整的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公式计算多边形的面积 + * 注意:点必须按顺时针或逆时针顺序排列 + * @param points 多边形的顶点坐标数组,每个点是一个长度为2的数组[x,y] + * @return 多边形的面积 + * @throws IllegalArgumentException 如果points为null或包含少于3个点 + */ + public static double calculatePolygonArea(double[][] points) { + if (points == null || points.length < 3) { + throw new IllegalArgumentException("多边形必须至少有3个点"); + } + + 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.length != 2 || next.length != 2) { + throw new IllegalArgumentException("每个点必须是长度为2的数组[x,y]"); + } + + area += (current[0] * next[1]) - (next[0] * current[1]); + } + + 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