zoukankan      html  css  js  c++  java
  • R语言中for循环和while循环求1100的和

    1、for循环

    sum = 0
    for (i in 1:100) 
    {
      sum = sum + i 
    }
    print(sum)

    1-100内偶数的和

    sum = 0
    for (i in 1:100) {
      if (i %% 2 == 0)
      {
        sum = sum + i
      }
    }
    print(sum)

    扩展:

    a <- c(2,4,5,7)
    b <- c(3,4,1,3)
    c <- data.frame(a,b)
    c
    sum = 0
    for (i in c$b) {
      sum = sum + i
    }
    print(sum)

     

      

    2、while循环

    sum = 0
    i = 100
    while (i > 0) {
      sum = sum + i
      i = i - 1
    }
    print(sum)

    sum = 0
    i = 1
    j = 100
    while (i <= j) {
      sum = sum + i
      i = i + 1
    }
    print(sum)

    求1-100内奇数的和

    sum = 0
    i = 100
    while (i > 0) {
      if (i %% 2 != 0)
      {
        sum = sum + i
      }
      i = i - 1
    }
    print(sum)

  • 相关阅读:
    数据结构 1
    MyBatis 7
    MyBatis 6
    MyBatis 5
    MaBatis 4
    MyBatis 3
    目录和文件管理
    Linux常用命令精讲
    Sentos7.4安装说明
    RIP
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14698517.html
Copyright © 2011-2022 走看看