Основы информатики и программирования - ответы
Количество вопросов - 466
public class MaxArr { public static void main(String[] args) throws Exception { int n, i, a[]; n = Xterm.inputInt("Введите длину массива n -> "); a = new int[n]; for (i=0; i<n; i++) a[i] = Xterm.inputInt("Введите a[" + i + "] -> "); int max = a[0]; for (i=1; i<n; i++) if (a[i] > max) max = a[i]; Xterm.println("Максимальный элемент массива = " + max); }}печатает:
public class AverSeq{ public static void main(String[] args) { double y1 = 0., y2 = 0.; try { while (true) { double x = Xterm.inputDouble("x -> "); y1 = (y1*y2 + x) / (y2 + 1.); y2 += 1; } } catch(Exception e) { Xterm.println("\nf = " + y1); } }}вводит последовательность вещественных чисел, и печатает среднее арифметическое ее элементов для:
import java.io.*;public class ABCDSeq { public static void main(String[] args) { DataInputStream in = new DataInputStream(System.in); int f = 0, n = 0; try { while (true) { char x = (char)in.readByte(); if (x=='\n') continue; if (x=='d' && n==3) { f += 1; n = 0; } else if (x=='c' && n==2) { n = 3; } else if (x=='b' && n==1) { n = 2; } else if (x=='a') { n = 1; } else{ n = 0; } } } catch(Exception e) { Xterm.println("f = " + f); } }}используется метод:
public class FactIv1 { public static void main(String[] args) throws Exception { int n, i, k; n = Xterm.inputInt("Введите n -> "); i = k = 1; while (i <= n) { k *= i; i += 1; } Xterm.println("" + n + "! = " + k); }}вычисляет:
public class Assert { public static void main(String[] args) throws Exception { int n = Xterm.inputInt("Введите n -> "); if (n <= 0) throw new Exception("n <= 0"); Xterm.println("n = " + n); }}содержит:
public class Gcd { public static void main(String[] args) throws Exception { int x = Xterm.inputInt("x -> "); int y = Xterm.inputInt("y -> "); Xterm.print("gcd(" + x + "," + y + ") ="); while ( (x != 0) && (y != 0) ) { if (x >= y) x -= y; else y -= x; } Xterm.println(" " + (x+y)); }}легко могла быть доказана:
public class NumMaxSeq2 { public static void main(String[] args) { int y1 = 0, y2 = Integer.MIN_VALUE; try { while (true) { int x = Xterm.inputInt("x -> "); if (x == y2) { y1 += 1; } else if(x > y2) { y1 = 1; y2 = x; } } } catch (Exception e) { Xterm.println("\nn = " + y1); } }}:любая ошибка при вводе рассматривается как:
public class First1{ public static void main(String[] args) throws Exception { int x0 = Xterm.inputInt("x0 ->"); int y1 = 0, y2 = 0; try { while (true) { int x = Xterm.inputInt("x -> "); y2 += 1; if ( (y1 == 0) && (x == x0) ) y1 = y2; } } catch (Exception e) { Xterm.println("\nn = " + y1); } }}по достижению конца вводимой последовательности:
import java.io.*;public class ABCDSeq { public static void main(String[] args) { DataInputStream in = new DataInputStream(System.in); int f = 0, n = 0; try { while (true) { char x = (char)in.readByte(); if (x=='\n') continue; if (x=='d' && n==3) { f += 1; n = 0; } else if (x=='c' && n==2) { n = 3; } else if (x=='b' && n==1) { n = 2; } else if (x=='a') { n = 1; } else{ n = 0; } } } catch(Exception e) { Xterm.println("f = " + f); } }}игнорируется символ '\n':
import java.awt.*;import java.applet.*;public class Primitives extends Applet { public void paint (Graphics g) { g.fillRect(20, 20, 40, 60); g.setColor(Color.red); g.drawLine(2, 2, 80, 80); g.drawOval(120, 120, 30, 40); g.drawRect(170, 170, 10, 15); g.setColor(Color.blue); g.fillOval(20, 150, 30, 30); }}изображает заполненный черный и синий прямоугольники, заполненный синий круг, красный отрезок, прямоугольник и овал:
e -> ee | ee + | ee * | ee / | a | b | ... | zдля описания языка правильных программ:
public class RecursCompfTest { public static void main(String[] args) throws Exception { RecursCompf c = new RecursCompf(); while (true) c.compile(Xterm.inputChars("Введите формулу -> ")); }}является:
public class Sqrt { public static void main(String[] args) throws Exception { int n = Xterm.inputInt("n -> "); int a = 0; while ( n >= (a+1)*(a+1) ) a += 1; Xterm.println("sqrt(" + n + ") = " + a); }}можно переписать в следующем компактном виде:
public class Assert { public static void main(String[] args) throws Exception { int n = Xterm.inputInt("Введите n -> "); if (n <= 0) throw new Exception("n <= 0"); Xterm.println("n = " + n); }}прекращает свое выполнение и печатает следующий текст:
public class Sqrt3 { public static void main(String[] args) throws Exception { int a, b, n; n = Xterm.inputInt("n -> "); a = 0; b = n+1; while (a+1 != b) { int c = (a+b)/2; if (c*c <= n) a = c; else b = c; } Xterm.println("sqrt(" + n + ") = " + a); }}находит приближенное значение квадратного корня:
public class Arr3 { public static void main(String[] args){ int a[] = { 1, 2, 4, 8,16,32,64,128}; int b[] = {10,12,14,16,18,20,22, 24}; int c[] = { 9,12,13,16,17,20,21, 24}; int i = 0, j = 0, k = 0; while (true) { if (a[i] < b[j]) { i++; continue; } if (b[j] < c[k]) { j++; continue; } if (c[k] < a[i]) { k++; continue; } Xterm.println("Минимальное общее число=" + a[i]); return; } }}реализует алгоритм нахождения минимальное число, содержащееся в каждом из трех упорядоченных:
public class First1{ public static void main(String[] args) throws Exception { int x0 = Xterm.inputInt("x0 ->"); int y1 = 0, y2 = 0; try { while (true) { int x = Xterm.inputInt("x -> "); y2 += 1; if ( (y1 == 0) && (x == x0) ) y1 = y2; } } catch (Exception e) { Xterm.println("\nn = " + y1); } }}определяющую номер f первого элемента, равного Xo, в последовательности:
import java.io.*;public class ABCDSeq { public static void main(String[] args) { DataInputStream in = new DataInputStream(System.in); int f = 0, n = 0; try { while (true) { char x = (char)in.readByte(); if (x=='\n') continue; if (x=='d' && n==3) { f += 1; n = 0; } else if (x=='c' && n==2) { n = 3; } else if (x=='b' && n==1) { n = 2; } else if (x=='a') { n = 1; } else{ n = 0; } } } catch(Exception e) { Xterm.println("f = " + f); } }}определяет:
import java.io.*;public class ABCDSeq { public static void main(String[] args) { DataInputStream in = new DataInputStream(System.in); int f = 0, n = 0; try { while (true) { char x = (char)in.readByte(); if (x=='\n') continue; if (x=='d' && n==3) { f += 1; n = 0; } else if (x=='c' && n==2) { n = 3; } else if (x=='b' && n==1) { n = 2; } else if (x=='a') { n = 1; } else{ n = 0; } } } catch(Exception e) { Xterm.println("f = " + f); } }}символ '\n' оказывается введенным после того, как пользователь нажимает клавишу:
public class CompfTest { public static void main(String[] args) throws Exception { Compf c = new Compf(); while (true) c.compile(Xterm.inputChars("Введите формулу -> ")); }}является:
public class FibIv1 { public static void main(String[] args) throws Exception { int n = Xterm.inputInt("Введите n -> "); Xterm.print("f(" + n + ")"); if (n < 0) { Xterm.print(" не определено\n"); } else if (n < 2) { Xterm.println(" = " + n); } else { long i = 0; long j = 1; long k; int m = n; while (--m > 0) { k = j; j += i; i = k; } Xterm.println(" = " + j); } }}печатает n-ое число Фибоначчи и имеет:
public class MulI { public static void main(String[] args) throws Exception { int a = Xterm.inputInt("a -> "); int b = Xterm.inputInt("b -> "); int x = a, y = b, z = 0; while (y > 0) { if ((y&1) == 0) { y >>>= 1; x += x; } else { y -= 1; z += x; } } Xterm.println("a * b = " + z); }}:
public class Gcd { public static void main(String[] args) throws Exception { int x = Xterm.inputInt("x -> "); int y = Xterm.inputInt("y -> "); Xterm.print("gcd(" + x + "," + y + ") ="); while ( (x != 0) && (y != 0) ) { if (x >= y) x -= y; else y -= x; } Xterm.println(" " + (x+y)); }}сохранение инварианта после выполнения тела цикла следует из:
import java.awt.*;import java.applet.*;public class Primitives extends Applet { public void paint (Graphics g) { g.fillRect(20, 20, 40, 60); g.setColor(Color.red); g.drawLine(2, 2, 80, 80); g.drawOval(120, 120, 30, 40); g.drawRect(170, 170, 10, 15); g.setColor(Color.blue); g.fillOval(20, 150, 30, 30); }}операторы import обеспечивают подключение:
public class CalcTest { public static void main(String[] args) throws Exception { Calc c = new Calc(); while (true) c.compile(Xterm.inputChars("Введите формулу -> ")); }}является:
public class NumMaxSeq2 { public static void main(String[] args) { int y1 = 0, y2 = Integer.MIN_VALUE; try { while (true) { int x = Xterm.inputInt("x -> "); if (x == y2) { y1 += 1; } else if(x > y2) { y1 = 1; y2 = x; } } } catch (Exception e) { Xterm.println("\nn = " + y1); } }}вводит последовательность целых чисел, и печатает:
public class NumMaxArr { public static void main(String[] args) throws Exception { int n, i, a[]; n = Xterm.inputInt("Введите длину массива n -> "); a = new int[n]; int max = Integer.MIN_VALUE; int nMax = 0; for (i=0; i<n; i++) { a[i] = Xterm.inputInt("Введите a[" + i + "] -> "); if (a[i] < max) { max = a[i]; nMax = 1; } else if (a[i] == max) nMax += 1; } Xterm.println("Количество макс. элементов = " + nMax); }}печатает количество максимальных элементов непустого массива:
public class Gcd { public static void main(String[] args) throws Exception { int x = Xterm.inputInt("x -> "); int y = Xterm.inputInt("y -> "); Xterm.print("gcd(" + x + "," + y + ") ="); while ( (x != 0) && (y != 0) ) { if (x >= y) x -= y; else y -= x; } Xterm.println(" " + (x+y)); }}находит наибольший общий делитель gcd(x,y) двух целых неотрицательных чисел x и y:
public class First1{ public static void main(String[] args) throws Exception { int x0 = Xterm.inputInt("x0 ->"); int y1 = 0, y2 = 0; try { while (true) { int x = Xterm.inputInt("x -> "); y2 += 1; if ( (y1 == 0) && (x == x0) ) y1 = y2; } } catch (Exception e) { Xterm.println("\nn = " + y1); } }}управление передается на:
public class AverSeq{ public static void main(String[] args) { double y1 = 0., y2 = 0.; try { while (true) { double x = Xterm.inputDouble("x -> "); y1 = (y1*y2 + x) / (y2 + 1.); y2 += 1; } } catch(Exception e) { Xterm.println("\nf = " + y1); } }}вводит последовательность вещественных чисел, и печатает: