java求n个整数的最大公约数

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验报告三JA VA程序设计基础

1.实验目的

熟练运用分支、循环等语句控制程序流程,掌握方法的声明和调用,以及字符串。掌握使用命令行参数作为输入数据的方法,找出程序错误位置和出错原因。

2.实验内容

():书上60页,2-26求N个整数的最大公约数。

代码:

Gys.java——文件名

public class Gys {

public static int gys(int a,int b)

{

int temp;

while(b!=0)

{

temp=a%b;

a=b;

b=temp;

System.out.print("gys("+a+","+b+")=");——输出运算过程

}

System.out.println(a);——输出最大公约数

return a;

}

public static void main(String[] args) {

int n=5,x,y,temp;

int a[]={12,60,160,64,80};

temp=a[0];

for(int i=0;i

x=temp;

y=a[i+1];

temp=gys(x,y);

}

System.out.print(temp);——输出n个数的最大公约数

}

}

运行结果:

(2)验证性实验:书上P54例2.10从标准输入流中读取一行字符串再转换成整数。

代码:

Input.java——文件名

import mypackage.*;

public class Input {

public static String readLine()throws java.io.IOException

{

System.out.println("输入一行字符串,以回车换行符结束");

byte buffer[]=new byte[512];

int count=System.in.read(buffer);

System.in.close();

return(count==-1)?null:new String(buffer,0,count-2);

}

public static void main(String args[])throws java.io.IOException { String s=readLine();

int value=MyInteger.parseInt(s);

System.out.println("MyInteger.toString("+value+",2)="+MyInteger.t oString(value,2));

System.out.println("MyInteger.toString("+value+",16)="+MyInteger. toString(value,16));

}

}

MyInteger.java——文件名

package mypackage;

public class MyInteger {

public static int parseInt(String s) throws NumberFormatException {

if(s==null)

throw new NumberFormatException("null");

char ch=s.charAt(0);

int value=0,i=0,sign=1,radix=0;

if(ch>='1'&&ch<='9'||ch=='+'||ch=='-')

{

radix=10;

if(ch=='+'||ch=='-')

i++;

sign=ch=='-'?-1:1;

}

else if(ch=='0'&&s.charAt(1)!='x')

{

radix=8;

i++;

}

else if(ch=='0'&&s.charAt(1)=='x')

{

radix=16;

i+=2;

}

else throw new NumberFormatException("整数不能识别\'"+ch+"\'字符");

while(i

{

ch=s.charAt(i++);

if(ch>='0'&&ch-'0'

value=value*radix+ch-'0';

else if(radix==16&&ch>'a'&&ch<='f')

value=value*radix+ch-'a'+10;

else if(radix==16&&ch>'A'&&ch<='F')

value=value*radix+ch-'A'+10;

else throw new NumberFormatException(radix+"进制整数不能识别\'"+ch+"\'字符");

}

return value*sign;

}

public static String toString(int value,int radix)

{

if(radix==10)

return value+"";

if(radix==2||radix==4||radix==8||radix==16)

{

int mask,n=0;

for(mask=radix-1;mask>0;mask>>>=1)

n++;

相关文档
最新文档