为什么这个简单的程序不起作用?
Why this easy program isn't working?
#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
, ++i
或i++
而不是1+1
。
在for循环的末尾有一个分号,它使循环不做任何事情。
你运行你的循环只要i = 100
总是为真。我也怀疑你指的是i == 100
,因为它总是错误的。你最好写i < 100
或i <= 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
}
相关文章:
- 为什么使用数组元素查找最大数字的程序不起作用?
- 用于拆分空格字符串的程序不起作用
- 反转一个数字程序不起作用,为什么?
- C++从句子中删除给定字符的程序不起作用
- 为什么当我选择>250000个采样点时,程序不起作用?
- 我的C 程序不起作用
- C++加密程序不起作用
- 发送到64位应用程序不起作用
- 猪拉丁程序不起作用
- 结构程序不起作用
- 为什么程序不起作用
- 找不到WCHAR.H文件-Xcode 9.0中断QT创建者 - 旧修复程序不起作用
- C++为什么我的程序不起作用..:S.
- C++帮助!程序不起作用
- 如果我将类声明为常量,程序不起作用...而不是康特斯普?
- 为什么我的C++程序不起作用
- c++11-实现Promise的示例程序不起作用
- 为什么我的程序不起作用以及如何阻止它快速关闭
- 我的火狐扩展程序不起作用。使用C++XPCOM组件的Firefox扩展(XPI文件)的结构是什么?
- std::在C++中设置删除程序不起作用