从a到b的数字相乘

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

Multiplication of numbers from a to b

问题

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

a = 2;
b = 6;

2 * 3
2 * 4
...
2 * 6

我有自己的算法:

void main()
{
    int dist = 1;
    int a = 2;
    int b = 5;
    for (int i = a; a <= b; a++) {
        printf("%d", a * a++);
    }
}

但它不正确。

英文:

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

a = 2;
b = 6;

2 * 3
2 * 4
...
2 * 6

I have my algorithm:

void main()
{
    int dist = 1;
    int a = 2;
    int b = 5;
    for (int i = a; a &lt;= b; a++) {
        printf(&quot;%d&quot;, a * a++);
    }
}

but it doesn't work correct

答案1

得分: 5

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

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

它会输出:

> 2 * 2 = 4
> 
> 2 * 3 = 6
> 
> 2 * 4 = 8
> 
> 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:

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

which prints:

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

答案2

得分: 0

int main() {
    int a = 2;
    int b = 6;
    int result = 1;  // 初始化结果变量为1以进行乘法运算

    // 从a到b执行乘法运算
    for (int i = a; i <= b; i++) {
        result *= i;
    }

    printf("从%d到%d的乘法结果是:%d\n", a, b, result);

    return 0;
}
英文:
int main() {
int a = 2;
int b = 6;
int result = 1;  // Initialize the result variable to 1 for multiplication

// Perform multiplication from a to b
for (int i = a; i &lt;= b; i++) {
    result *= i;
}

printf(&quot;The multiplication result from %d to %d is: %d\n&quot;, a, b, result);

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:

确定