package com.test;
import java.awt.Graphics;
import java.io.InputStream;
import java.util.Scanner;
import javax.swing.JFrame;
public class test1 extends JFrame{
public double A=0,B=0,C=0,D=0,delta;
public double[] x=new double[100],y=new double[100];
public static double a,b;
public double e=0.0;//误差
public double n;//浮点数个数
int flag=0;
public void input(){
System.out.println("请输入坐标点个数n");
// 属于标准的输入流
InputStream is = System.in;
Scanner scan = new Scanner(is);
n = scan.nextInt();
// System.out.println(n);
System.out.println("请输入坐标点(x,y)");
for(int i=0;i
String a1,b1;
System.out.println("输入第"+(i+1)+"个点的坐标");
System.out.println("横坐标: ");
a1 = scan.next();
x[i]=Double.parseDouble(a1);
System.out.println("纵坐标 :");
b1 = scan.next();
y[i]=Double.parseDouble(b1);
// System.out.println("x="+x[i]+ " "+"y="+y[i]);
A+=x[i]*x[i];
B+=x[i];;
C+=x[i]*y[i];
D+=y[i];
}
delta=A*n-B*B;
if(delta<1e-10&&delta>(-1e-10)){
System.out.println("Error!Divide by zero");
}
else{
a=(C*n-B*D)/delta;
b=(A*D-C*B)/delta;
}
}
public void output(){
System.out.println("逼近直线为:");
if(b>=0){
System.out.println("y="+a+"x"+"+"+b);
}else
{
System.out.println("y="+a+"x"+"-"+(-b));
}
for(int k=0;k
}
System.out.println("误差为:"+e);
flag=1;
this.repaint();
}
public void paint(Graphics g){
if(flag==1){
if(b!=0)
g.drawLine(0,(int)b,100,(int)(100*a+b));
else
g.drawLine(0,0,100,100*(int)a);
}
}
public static void main(String agrs[]){
test1 t1=new test1();
t1.input();
t1.output();
t1.setSize(400, 300);
t1.setVisible(true);
t1.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
//这里画直线不是很好控制但是我可以告诉你的就是g.drawLine(x1,y1,x2,y2)就是绘制(x1,y1)到(x2,y2)的直线,单位是像素,在JFrame这个框架上左上角为(0,0)
如果你是新学的话,学下javafx吧,做桌面程序很简单,现在蛮成熟的了