编译器错误,包括“<”标记之前的初始化程序

Compiler Errors including initializer before '<' token

我正在为 Project Euler 谜题之一编写这段代码以练习编码,我遇到了一些我认为是语法错误的问题。我在这里做错了什么?

#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

这里有几个问题:

  1. for 循环的各个部分应该用分号 (;) 分隔,而不是逗号 (,)
  2. 在第一个 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

for uses 的语法;区分三个表达式(初始化、条件和更新)因此你应该写:

for (int i = 100; i < smallestMultiple; i+=2)

而不是:

for (int i = 100, i < smallestMultiple, i+2)

如果您想将 i 从 100 迭代到 smallestMultiple,增量为 2