我继续得到这个“错误C2059”C ++

时间:2013-11-09 17:09:31

标签: c++ visual-c++

我收到此错误

error C2059: syntax error : 'if'

这是我的代码

// N.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

int main ()
{
    int x,y,n,i,m;
    std::cout<<"please enter a number";
    i=0;
    std::cin>>n;
    for (x=1;x=n;x++)
        for (y=1;y=n;y++)
        if (x=y) m=x;
        else;
    while (x!=y) ;
    do
    {
        if (x>y) x=x-y;
        else y=y-x;
        m=x;
    }
    if (m=1) i=i+1;
    std::cout<<i;
    return 0;
}

问题是什么?

我正在使用microsoft visual studio 2008

2 个答案:

答案 0 :(得分:1)

问题是在do { ... }编译器期待条件之后:

do
{
    if (x>y) x=x-y;
    else y=y-x;
    m=x;
} while (condition);

此外,您的代码似乎根本不正确。例如,您的if (x=y)条件可能如下:if (x==y),以及其他......

答案 1 :(得分:0)

您的for声明中有错误 使用==进行比较,而不是作为作业的= 另外,使用<<=作为对照。可以在循环中跳过==条件。

有关未来有助于预防这些问题的建议:对forifelsewhile使用“{”和“}”。

例如:

for (x=1;x=n;x++)
{  // Insert this line.
    for (y=1;y=n;y++)
    {  // Insert this line.
        if (x=y)
        {
           m=x;
        }
        else
        {
           ;
        }
    } // End of for y
}  // End of for x

大括号和缩进有助于在代码审查期间发现错误。大多数编码样式都需要大括号,即使对于单个语句也是如此。

此外,使用空格使代码更具可读性。它们不会影响构建时间或代码生成,但在阅读代码时确实有帮助:
for (x = 1; x <= n; x++)