从a到b的数字相乘

huangapple go评论119阅读模式
英文:

Multiplication of numbers from a to b

问题

我需要编写一个算法,用于在不需要输入(scanf)的情况下计算从a到b的数的乘积。就像这样:

  1. a = 2;
  2. b = 6;
  3. 2 * 3
  4. 2 * 4
  5. ...
  6. 2 * 6

我有自己的算法:

  1. void main()
  2. {
  3. int dist = 1;
  4. int a = 2;
  5. int b = 5;
  6. for (int i = a; a <= b; a++) {
  7. printf("%d", a * a++);
  8. }
  9. }

但它不正确。

英文:

I need to write algorithm, that multiplies numbers from a to b without input (scanf). Like this:

  1. a = 2;
  2. b = 6;
  3. 2 * 3
  4. 2 * 4
  5. ...
  6. 2 * 6

I have my algorithm:

  1. void main()
  2. {
  3. int dist = 1;
  4. int a = 2;
  5. int b = 5;
  6. for (int i = a; a &lt;= b; a++) {
  7. printf(&quot;%d&quot;, a * a++);
  8. }
  9. }

but it doesn't work correct

答案1

得分: 5

这是因为你在上面的示例中对 a 进行了两次增加 (a++)。同时你有点混淆了 ai。正确的代码如下:

  1. int a = 2;
  2. int b = 5;
  3. for (int i = a; i <= b; i++)
  4. {
  5. printf("%d * %d = %d\n", a, i, a * i);
  6. }

它会输出:

  1. > 2 * 2 = 4
  2. >
  3. > 2 * 3 = 6
  4. >
  5. > 2 * 4 = 8
  6. >
  7. > 2 * 5 = 10
英文:

This is because you are increasing a (a++) two times in your example above. Also you mixed up a and i a little bit. Correct one is:

  1. int a = 2;
  2. int b = 5;
  3. for (int i = a; i &lt;= b; i++)
  4. {
  5. printf(&quot;%d * %d = %d\n&quot;, a, i, a * i);
  6. }

which prints:

> 2 * 2 = 4
>
> 2 * 3 = 6
>
> 2 * 4 = 8
>
> 2 * 5 = 10

答案2

得分: 0

  1. int main() {
  2. int a = 2;
  3. int b = 6;
  4. int result = 1; // 初始化结果变量为1以进行乘法运算
  5. // 从a到b执行乘法运算
  6. for (int i = a; i <= b; i++) {
  7. result *= i;
  8. }
  9. printf("从%d到%d的乘法结果是:%d\n", a, b, result);
  10. return 0;
  11. }
英文:
  1. int main() {
  2. int a = 2;
  3. int b = 6;
  4. int result = 1; // Initialize the result variable to 1 for multiplication
  5. // Perform multiplication from a to b
  6. for (int i = a; i &lt;= b; i++) {
  7. result *= i;
  8. }
  9. printf(&quot;The multiplication result from %d to %d is: %d\n&quot;, a, b, result);
  10. return 0;

}

huangapple
  • 本文由 发表于 2023年6月18日 23:23:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76501244.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定