如何使用接班人和predecessor ​​Scala中做乘法乘法、如何使用、中做、Scala

2023-09-11 02:41:21 作者:暖心

我是编程语言的初学者。现在,我工作的一个Scala的项目,这就要求我们要计算的之在产品和幂的两个非负整数没有使用任何数学函数和迹象,但只允许使用继任和 predecessor ​​。该功能也算给我们。所以,我需要定义除了在这两个整数的条款,然后定义乘法计算乘法加法的条款和指数。到目前为止,我只拿出的解决方案让之。能否请你帮我获得了其他地方?我想,(如果firstNum = 1,secondNum = 3)这两个产品可以通过使用 sum_1(sum_1(sum_1(一,0),),一个)但是我真不'获得知道如何在斯卡拉code写。非常感谢!

 进口io.StdIn._

VAL NUM =的readLine(\ñ\ n有关计数的总和,乘两个整数和指数\ n请在(X,Y)的格式输入这两个整数:。)
VAL逗号= num.indexOf(,)

VAL最后= num.indexOf())
VAL firstNum = num.substring(1,逗号).toInt
VAL secondNum = num.substring(逗号+ 1,最后一个).toInt

高清sum_1(一:智力,B:智力):INT = {
  高清SUCC(一:智力):INT = A + 1
  DEF preD(二:智力):智力= B  -  1
  如果(b将1)一个
  其他 {
    SUCC(一)
    preD(二)
    sum_1(SUCC(a)中,$ P $概率pd(b))的
  }
}


//乘法


//求幂


的println(1.总和为+ sum_1(firstNum,secondNum)+。)
的println(2.乘法。)
的println(3,求幂的。)
 

解决方案

您将拥有的功能如下设置:

 高清SUCC(一:智力)= A + 1

DEF preD(A:强度)= A-1

高清总和(一:智力,B:智力):INT =
  如果(b将1)一个
  别的总和(SUCC(a)中,$ P $概率pd(b))的

高清MUL(一:智力,B:智力):INT =
  如果(B == 0)0
  否则,如果(二== 1)一个
  别的总和(MUL(一个,$ P $概率pd(b))的,一)

高清EXP(A:智力,B:智力):INT =
  如果(b将1)1
  别的穆尔(实验值(一个,$ P $概率pd(b))的,一)
 

I am a beginner of programming language. Right now, I am working on a Scala project, which requires us to calculate the sum of the product and the exponentiation of two non-negative integers without using any Math functions and signs but only allows to use successor and predecessor. The functions do count for us. So I need to define addition in terms of those two integers, then define multiplication in terms of addition and exponents in terms of multiplication. So far, I've only come up with the solution for getting sum. Could you please help me to obtain the other parts? I think (if firstNum = 1, secondNum = 3) the product of these two can be obtained by using sum_1(sum_1(sum_1(a,0),a),a) But I really don't know how to write it in Scala code. Many thanks!

import io.StdIn._

val num = readLine("\n\nFor counting the sum, multiplication and exponentiation of two integers.\nPlease enter those two integers in (x,y) format: ")
val comma = num.indexOf(",")

val last = num.indexOf(")")
val firstNum = num.substring(1,comma).toInt
val secondNum = num.substring(comma+1,last).toInt

def sum_1(a:Int,b:Int): Int = {
  def succ(a:Int): Int = a + 1
  def pred(b:Int): Int = b - 1
  if (b < 1) a
  else {
    succ(a)
    pred(b)
    sum_1(succ(a), pred(b))
  }
}


//multiplication


//exponentation


println("1.The sum is " + sum_1(firstNum, secondNum) + ".")
println("2.The multiplication is .")
println("3.The exponentation is .")

解决方案

You will have the following set of functions:

def succ(a:Int) = a+1

def pred(a:Int) = a-1

def sum(a:Int,b:Int):Int =
  if(b<1) a
  else sum(succ(a),pred(b))

def mul(a:Int,b:Int):Int =
  if(b==0) 0 
  else if(b==1) a
  else sum(mul(a,pred(b)),a)

def exp(a:Int, b:Int):Int =
  if(b<1) 1
  else mul(exp(a,pred(b)),a)