0
点赞
收藏
分享

微信扫一扫

微信小程序---支付

ZMXQQ233 2024-06-23 阅读 43

1、用repeat、for、while计算从1-10的所有整数的平方和

2、编写一个函数,给出两个正整数,计算他们的最小公倍数

3、编写一个函数,让用户输入姓名、年龄,得出他明年的年龄。用paste打印出来。例如:"Hi xiaoming you will be 35 next year"

4、编写一个递归函数,实现根据元素索引,得到Fibonacci序列(1,1,2,3,5,8,13…)的值,即f(n)=f(n-1)+f(n-2),n>=3。其中f(1)=1,f(2)=1。

并计算f(20)的值。

5、编写一个函数,将c(2,3,5,8,9,13,21,34)中能被3整除的元素,替换为0,并输出替换后的向量。

  1. 用repeat、for、while计算从1-10的所有整数的平方和

代码:

# 使用 repeat 循环计算

total <- 0

i <- 1

repeat {

total <- total + i^2

i <- i + 1

if (i > 10) {

break

}

}

print(paste("从1到10的所有整数的平方和为:", total))



# 使用 for 循环计算

total <- 0

for (i in 1:10) {

total <- total + i^2

}

print(paste("从1到10的所有整数的平方和为:", total))



# 使用 while 循环计算

total <- 0

i <- 1

while (i <= 10) {

total <- total + i^2

i <- i + 1

}

print(paste("从1到10的所有整数的平方和为:", total))

        截图:

                

  1. 编写一个函数,给出两个正整数,计算他们的最小公倍数

代码:

        

# 定义gcd函数  
gcd <- function(a, b) {
while (b != 0) {
temp <- b
b <- a %% b
a <- temp
}
return(a)
}

# 定义lcm函数
lcm <- function(x, y) {
return((x * y) / gcd(x, y))
}

# 读取用户输入
num1 <- as.integer(readline("请输入第一个正整数:"))
num2 <- as.integer(readline("请输入第二个正整数:"))

# 计算并打印LCM
result <- lcm(num1, num2)
print(paste("两个正整数的最小公倍数为:", result))

截图:

3、编写一个函数,让用户输入姓名、年龄,得出他明年的年龄。用paste打印出来。例如:"Hi xiaoming you will be 35 next year"

代码:

next_year_age <- function(name, age) {

  next_age <- age + 1

  print(paste("Hi", name, "you will be", next_age, "next year."))

}



name <- readline("请输入您的姓名:")

age <- as.integer(readline("请输入您的年龄:"))



next_year_age(name, age)

截图:

4、编写一个递归函数,实现根据元素索引,得到Fibonacci序列(1,1,2,3,5,8,13…)的值,即f(n)=f(n-1)+f(n-2),n>=3。其中f(1)=1,f(2)=1。

并计算f(20)的值。

代码:

fibonacci <- function(n) {

if (n <= 1) {

return(n)

} else {

return(fibonacci(n-1) + fibonacci(n-2))

}

}



n <- 20

print(paste("Fibonacci 序列第", n, "个元素的值为:", fibonacci(n)))

截图:

  1. 编写一个函数,将c(2,3,5,8,9,13,21,34)中能被3整除的元素,替换为0,并输出替换后的向量。

代码:

replace_divisible_by_3 <- function(lst) {

  for (i in 1:length(lst)) {

    if (lst[i] %% 3 == 0) {

      lst[i] <- 0

    }

  }

  return(lst)

}

c <- c(2, 3, 5, 8, 9, 13, 21, 34)

new_c <- replace_divisible_by_3(c)

print(paste("替换后的向量为:", new_c))

截图:

举报

相关推荐

0 条评论