【问题标题】:multiplying number from 1 to N while adding 2 every time将数字从 1 乘到 N,同时每次加 2
【发布时间】:2021-06-18 08:39:19
【问题描述】:

我必须编写一个将数字从 1 乘到 N 的 C 程序。 N 被扫描。在乘法之前,我必须将每个数字增加 2。 例如:N = 3 => (1+2)(2+2)(3+2) = 60 我只需要使用while循环和打印和扫描功能。

示例程序:

Enter the value of N: 4
The result of multiplication: 360

这是我的代码,我不确定这有什么问题。请帮忙。

#include <stdio.h>



    int N;
    int count=1, ii, result;
    printf("Enter the value of N:");
    scanf("%d", &N);

    while (count<=N)
    {
        count ii = count + 2;
        ii = ii * ii ;  //three
                count++;
        
    }
    result = ii;
    printf("The result of multiplication: %d", result);

    return 0;

}

【问题讨论】:

  • 看起来你在找(N+2)! / 2
  • 提示:x *= xx = x * x 的简写形式。
  • count ii = ... 没有任何意义,因为 countii 都是变量。

标签: c loops while-loop


【解决方案1】:

如果您正在寻找该系列作为总和:

const int N = 3;
int c = 1;
for (int i = 1; i <= N; ++i) {
  c *= (i + 2);
}

或者以更 C 风格的形式:

const int N = 3;
int c = 1;
for (int i = 0; i < N; ++i) {
  c *= (i + 1 + 2);
}

【讨论】:

  • 我必须使用while循环,因为我们还没有学习for循环
  • 您可以轻松地将其修改为使用while。学习for 循环实际上需要十分钟。它并不复杂,它会在未来几年为您服务。
【解决方案2】:
   int main()
   {
       int N;
       int count=1, ii = 1, result;
       printf("Enter the value of N:");
       scanf("%d", &N);
       while (count<=N)
       {
           ii = ii * ( count + 2 };
           count++;
       }
       result = ii;
      printf("The result of multiplication: %d", result);
      return 0;
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-27
    • 2012-10-15
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多