《Java程序设计》课程代码题(七)

1.《向量》

编写向量类MyVector,完成以下任务:
1)使用一个一维数组构造一个向量类(元素类型为double)
2)实现向量的点积 MyVector dot(MyVector v2) ,x·y = (x0y0,x1y1,…,xn-1*yn-1)
3) 实现向量的加法 MyVector add(MyVector v2), x+y = (x0+y0,x1+y1,…,xn-1+yn-1)
4) 实现向量的String toString()方法;输出形式(x0,x1,…,xn-1),每个元素保留2位小数
5) 向量中一个私有变量double[] array,表示向量数据
6) 向量中一个私有变量int n,表示维度

写主方法里面,验证以上方法。
输入两个长度一致的数组,构造两向量,向量进行点积和求和运算,并输出结果
输入要求
多组数据
长度n
数组1各元素
数组2各元素

输出要求
点积后的向量结果//注意逗号后有个空格
向量相加后的结果//注意逗号后有个空格
输入

3
1 2 3
3 2 1

5
2.0 3.0 1 2 3
1 2 3 2.0 3.0

输出

(3.00, 4.00, 3.00)
(4.00, 4.00, 4.00)
(2.00, 6.00, 3.00, 4.00, 9.00)
(3.00, 5.00, 4.00, 4.00, 6.00)

代码



import java.text.DecimalFormat;
import java.util.Scanner;

public class Main {
   

    public static void main(String[] args) {
   
 // write your code here
        Scanner sc=new Scanner(System.in);
        while(sc.hasNext()){
   
            int n=sc.nextInt();
            double  [] v1=new double[n];
            double [] v2=new double[n];
            for(int i=0;i<n;i++)
                v1[i]=sc.nextDouble();
            for(int i=0;i<n;i++)
                v2[i]=sc.nextDouble();
            MyVector myV1=new MyVector(v1);
            MyVector myV2=new MyVector(v2);
            MyVector myV3=myV1.dot(myV2);
            MyVector myV4=myV1.add(myV2);
            System.out.println(myV3.toString());
            System.out.println(myV4.toString());


        }

    }
}
class  MyVector{
   
    private double []  array;
    private  int n;
    public MyVector(double []  _Vector){
   
        this.array=_Vector;
        this.n=_Vector.length;
    }


    public   MyVector  dot(MyVector vector){
   


        double []  ans=new  double[vector.n];
        for(int i=0;i<ans.length;i++)
            ans[i]=this.array[i]*vector.array[i];
        MyVector myVector=new MyVector(ans);
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一角灯辉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值