为什么这个简单的程序不起作用?

Why this easy program isn't working?

本文关键字:程序 不起作用 简单 为什么      更新时间:2023-10-16
#include <iostream>
#include <conio.h>
int main()
{
    int i;
    for (i = 1; i = 100; 1 + 1);
    {
        std::cout << i << " = " << i *i << std::endl;
    }
    do 
    {
        std::cout << i << " = " << i *i << std::endl;
    } while (i = 100)
    getch();
}

为什么不工作。给立方数从1到100的数是很简单的,它就打开了,什么也没发生。有人能帮忙吗?!我只是个初学者,解决不了这个问题。由于

你有很多错误,例如

for ( i = 1 ; i = 100 ; 1+1 ) ;
应:

for ( i = 1 ; i <= 100 ; i += 1 )

(注意移除了一个杂散的;以及其他变化)。

:

while ( i = 100 )
应:

while ( i <= 100 );

(注意添加了缺失的;以及从=<=的变化)。

您可能还想在do循环之前重新初始化i,并在循环中增加它:

i = 1;
do 
{
    std::cout << i << " = " << i * i << std::endl;
    i += 1;
} while (i <= 100);

do -while循环必须以分号结束。

要增加你的值必须写i=i+1, i+=1, ++ii++而不是1+1

在for循环的末尾有一个分号,它使循环不做任何事情。

你运行你的循环只要i = 100总是为真。我也怀疑你指的是i == 100,因为它总是错误的。你最好写i < 100i <= 100 (for和while循环)

你不能在循环之间重置i

最后但并非最不重要的是,您不会在while循环中增加i。所以这个循环要么永远不运行,要么永远运行,因为i永远不会改变。

#include <iostream>
#include <conio.h>
int main()
{
    int i;
    for (i = 1; i <= 100; ++i)
    {
        std::cout << i << " = " << i *i << std::endl;
    }
    i = 1; //Reset
    do 
    {
        std::cout << i << " = " << i *i << std::endl;
        i++;
    } while (i <= 100);
    getch();
}

我希望我都得到了。

#include <iostream>
// delete because this is unneeded and emits error on some compilers
//#include <conio.h>
int main ()
{
    int i  ;
    for ( i = 1 ; i <= 100 ; i++ ) // fix second and third expression and remove junk semicolon
    {
        std :: cout <<  i  << " = " << i *i << std :: endl ;
    }
    i = 1; // add
    do {
        std :: cout <<  i  << " = " << i *i << std :: endl ;
    } while ( (++i) <= 100 ); // change = to <=, update i and add semicolon
    // delete because this is unneeded and emits error on some compilers
    //getch () ;
}

for循环中的1+1是问题所在。你陷入了一个无限循环。您永远不会增加i,因此它永远不会达到100,也永远不会退出for循环。在其他答案中也有第二个错误。将for循环的i = 100更改为1 <= 100

你的for循环是错误的,你可能需要

#include <iostream>
#include <conio.h>
int main ()
{
    int i  ;
    for ( i = 1 ; i < 100 ; i++ )
    {
        std :: cout <<  i  << " = " << i *i << std :: endl ;
    }
    getch () ; //no clue what this is, but you probably know
}