java - 下面这段代码为什么会出现这个错误?怎么改?求指点?
PHPz
PHPz 2017-04-17 17:20:22
[Java讨论组]
/**
 * Created by guchenghao on 16/3/5.
 */
import java.util.Scanner;

public class lagrange {

    public static int sum(int x[],int y[],int m ) {

        int s = 0;

        int j = 0;
        int h = 0;

        while (j < y.length){
            h = lan(x,m,j);
            s += y[j]*h;
            j++;
        }
        return s;
    }

    public  static int lan(int x[],int m,int j) {
        int i;
        int h = 1;

        for (i = 0; i < x.length; i++) {

            if ( i == j) {
                continue;
            } else {
                h = h * ((m - x[i]) / (x[j] - x[i]));
            }
        }

        return h;
    }


    public static void main(String[] args) {

        int[] x = new int[100];
        int[] y = new int[100];

        Scanner scan = new Scanner(System.in);
        System.out.println("请输入组数:");
        int n = scan.nextInt();
        System.out.println("请输入插值基函数中未知量:");
        int m = scan.nextInt();

        System.out.println("请给X和Y两个数组赋初值:");
        for (int i = 0; i < n; i++) {
            System.out.println("请给X赋值:");
            x[i] = scan.nextInt();
            System.out.println("请给Y赋值:");
            y[i] = scan.nextInt();
        }
        int sumup;
        sumup = sum(x,y,m);
        System.out.println("插值基函数所得的结果为:" + sumup);
    }

}

PHPz
PHPz

学习是最好的投资!

全部回复(3)
PHPz
int[] x = new int[100];
int[] y = new int[100];
 while (j < y.length){
            h = lan(x,m,j);
            s += y[j]*h;
            j++;
        }
 for (i = 0; i < x.length; i++) {

            if ( i == j) {
                continue;
            } else {
                h = h * ((m - x[i]) / (x[j] - x[i]));
            }
        }

你先声明了100个元素的数组x,y,java 默认初始化都是0的,然后只赋值了前两个。但是在lan方法(i < x.length)和sum方法里(j < y.length)循环读取所有的值,用x[j] - x[i]肯定会出现 0-0的情况。

根据你程序的目的,解决方法如下:

  1. 根据参数n动态什么数组

        Scanner scan = new Scanner(System.in);
        System.out.println("请输入组数:");
        int n = scan.nextInt();
        System.out.println("请输入插值基函数中未知量:");
        int m = scan.nextInt();

        int[] x = new int[n];
        int[] y = new int[n];
  1. 将n传递给lan和sum方法

PS: 题主典型的面向过程编程, 将java当c用,无语也。。。

大家讲道理

异常信息写的很明白,h = h * ((m - x[i]) / (x[j] - x[i]));这行代码的除数变成0,导致算术运算异常。

迷茫

除数为零了。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号