Answer the question
In order to leave comments, you need to log in
How to output 2 values from a function?
Hello everyone, there is a function that counts the sum of the entered numbers and the number of positive numbers.
That is, the result of the function is 2 parameters: sum and pos , which must be passed to the main function.
How can this be done? I decided to combine them into an array and pass the data array, but I can’t call sum and pos separately inside println in fun main
fun main() {
// Рассчет кол-ва положительных чисел и суммы введенных чисел
print("Введите число N: ")
val n = readLine()?.toIntOrNull()
?.let { n ->
if (n > 0) {
println("Количество положительных чисел: ${calcPositiveAndSumByWhile(n)}")
println("Сумма чисел: ${calcPositiveAndSumByWhile(n)}")
} else {
println("Вы ввели не число\n")
}
}
?: println("Вы ввели не число\n")
// Рассчет НОД
print("Введите любое число: ")
val num = readLine()?.toIntOrNull()
?.let { num ->
if (num > 0) {
println(calcNOD(num))
} else {
println("Вы ввели не число\n")
}
}
?: println("Вы ввели не число\n")
}
fun calcPositiveAndSumByWhile(n: Int): Array<Int> {
var pos: Int = 0
var sum: Int = 0
var currentNumber: Int = 0
while (currentNumber < n) {
print("Введите число $currentNumber: ")
val m = readLine()?.toIntOrNull()
?.let { m ->
if (m > 0) {
pos++
sum += m
currentNumber++
} else {
sum += m
currentNumber++
}
}
?: println("Вы ввели не число\n")
}
return arrayOf(pos, sum)
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question