【问题标题】:c syntax problem, to print the sum of multiples of 3 and 5 under a n value [closed]c语法问题,在n值下打印3和5的倍数之和[关闭]
【发布时间】:2020-06-24 07:42:54
【问题描述】:

为什么会出现语法错误,我认为没有任何问题。谢谢.. 语法错误在第 2 行。

#include <stdio.h>
int main() {
    long int sum;
    int an;
    printf("Sum of multiples of three and five\nEnter the nth value\n>> ");
    scanf("%d",&an);
    sum=((3/2*an/3*(an/3+1))+(5/2*an/5*(an/5+1))-(15/2*an/15*(an/15+1)));
    printf("The sum of multiples of 3 and 5 under %d is %ld",an,sum);
}

【问题讨论】:

  • sum=(3/2*an/3*(an/3+1))+(5/2*an/5*(an/5+1))-(15/2*an/15*(an/15+1))..missing ;
  • 欢迎来到 Stack Overflow! 这个问题是由无法再重现的问题或简单的印刷错误引起的。虽然类似的问题可能是这里的主题,但这个问题的解决方式不太可能帮助未来的读者。这通常可以通过在发布前识别并仔细检查the shortest program necessary to reproduce the problem 来避免。
  • 然后向我们展示您拥有的代码,而不是您认为拥有的代码。
  • 当然不真实。您编辑添加了;,现在此代码不会重现您之前所说的问题。
  • test那个公式。您知道整数除法(3/2an/315/2...)的行为方式吗?

标签: c sum syntax-error


【解决方案1】:

缺少的; 是一个很容易修复的印刷错误,但这不是发布代码中的主要问题。

sum = ((3/2*an/3*(an/3+1))+(5/2*an/5*(an/5+1))-(15/2*an/15*(an/15+1)));
//      ^^^   ^     ^       ^^^   ^     ^       ^^^^   ^    ^^^^^   

此行无法提供正确答案,因为多个整数除法会“截断”(对整数类型执行操作,实际上不涉及浮点变量)中间值到整数。

通过将此评估拆分为几个函数,您可能会在代码可读性方面有所收获。

long int sum_of_multiples(int factor, int n)
{
    // Number of multiples of factor up to n.
    // E.g. 13 / 3 = 4  --> 3, 6, 9, 12 
    long int multiples = n / factor;
    
    // Sum of the multiples using Gauss's method.
    // 3 + 6 + 9 + 12 = 3 * (1 + 2 + 3 + 4) = 3 * (4 * (4 + 1)) / 2
    // Note that the product of an odd and an even number is always even
    return factor * (multiples * (multiples + 1) / 2);
}

long int sum_of_multiples_of_3_and_5_less_than_n(int n)
{
    if ( n < 1 )
        return 0;
    // The OP wrote "under", so I assume they want to exclude the number itself
    --n;
    return sum_of_multiples(3, n) + sum_of_multiples(5, n) - sum_of_multiples(15, n);
}

【讨论】:

  • 可读性是一个被低估的属性,特别是对于那些不必返回到 6 个月前编写的代码的新代码。
【解决方案2】:

; 放在第 7 行后,它工作正常。

【讨论】:

  • 我认为我的 gcc 坏了,我在 windows 上这样做,我安装了 mingw-minimal
  • 我在其他地方编译它可以工作,但不是在我的窗口上:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
  • 1970-01-01
  • 2021-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多