我正在为欧拉项目难题之一编写这段代码来练习编码,但我遇到了一些语法错误,我认为是这样。我在这里做错了什么?
#include <iostream>
#include <string>
using namespace std;
int main()
{
int smallestMultiple = 10000;
int sum = 1;
for (int i = 100, i < smallestMultiple, i+2)
{
for (int j = 20, j >=10, j--)
{
sum = sum + (i % j);
}
if (sum == 1)
{
smallestMultiple = i;
}
else
{
sum = 1;
}
}
cout<< "The smallest number easily divisible by the numbers 1 to 20 is " << smallestMultiple << "." << endl;
}
当我尝试编译此代码时收到以下错误。我缺少什么类型的语法?
smallMultiple.cpp:6: error: expected ‘;’ before ‘int’
smallMultiple.cpp: In function ‘int main()’:
smallMultiple.cpp:12: error: expected initializer before ‘<’ token
smallMultiple.cpp:32: error: expected primary-expression at end of input
smallMultiple.cpp:32: error: expected ‘;’ at end of input
smallMultiple.cpp:32: error: expected primary-expression at end of input
smallMultiple.cpp:32: error: expected ‘)’ at end of input
smallMultiple.cpp:32: error: expected statement at end of input
smallMultiple.cpp:32: error: expected ‘}’ at end of input
for 的语法;为了区分三个表达式(初始化、条件和更新),因此您应该编写:
for (int i = 100; i < smallestMultiple; i+=2)
而不是:
for (int i = 100, i < smallestMultiple, i+2)
如果你想以 2 为增量迭代 i 从 100 到smallestMultiple
这里有几个问题:
for
循环的各部分应以分号 (;
) 分隔,而不是逗号 (,
)for
循环中,i + 2
未存储在任何地方。假设您打算将 2
添加到 i
的值,则应该使用 i+=2
。因此,总而言之,您的
for
循环应如下所示:
for (int i = 100; i < smallestMultiple; i+=2)
{
for (int j = 20; j >=10; j--)
{
// rest of the code