读书人

if 和 while 的区别是什么?解决思路

发布时间: 2012-03-30 17:32:10 作者: rapoo

if 和 while 的区别是什么??
我写了个程序其中有一个交换数列的地方??
#include <iostream>
using namespace std;
int main()
{
int a[10001];
int t,k,d,f,n,i=0,g;
cin > > t;
for( k=0;k <t;k++)
{
cin > > n;
for( d=1;d <=n;d++)
cin > > a[d];
i=0;
for(f=1;f <=n;f++ )
{

if(a[f]!=f) ///就是这个地方的if 和while
{
g = a[f];
a[f] = a[g];
a[g] = g;
i++;
}
}
cout < < i < < endl;
}


return 0;
}


如果用if 会的到一个答案 但是用while 又会的到一个答案。 这是为什么??
那个大个帮帮忙哦??



[解决办法]


if 进行一次逻辑判断,根据判断逻辑结果决定是否操作;
while 进行一系列循环操作,可能执行 N 次 ...
[解决办法]
在这里if同while是没有区别的。完全可以替换。但是问题出在你的程序上。
int t,k,d,f,n,i=0,g;
cin > > t;
for( k=0;k <t;k++)
{
cin > > n;
for( d=1;d <=n;d++)
cin > > a[d];
你在cin分别是什么意思?!!!
cin > > n; 放的位置你认为妥当么?
cin > > a[d]; 你是不是想 a[d]=d; ???
云云....

[解决办法]
n=5;
if (n <10)
{
cout < < "hello " < < endl;
n++;
}

你觉得输出是什么?还是没有输出?最后n的值是多少,5还是6?


n=5
while (n <10)
{
cout < < "hello " < < endl;
n++;
}
同样的问题,现在输出是什么?n又是多少呢?
[解决办法]
; 7 : n = 5;

movDWORD PTR _n$[ebp], 5

; 8 : if(n < 10)

cmpDWORD PTR _n$[ebp], 10; 0000000aH
jgeSHORT $L339

; 10 : printf( "hello\n ");

pushOFFSET FLAT:??_C@_06KIKN@hello?6?$AA@; `string '
call_printf
addesp, 4

; 11 : n++;

moveax, DWORD PTR _n$[ebp]
addeax, 1
movDWORD PTR _n$[ebp], eax
$L339:


; 13 :
; 14 : n = 5;

movDWORD PTR _n$[ebp], 5
$L342:

; 15 : while(n < 10)

cmpDWORD PTR _n$[ebp], 10; 0000000aH
jgeSHORT $L343

; 17 : printf( "hello\n ");

pushOFFSET FLAT:??_C@_06KIKN@hello?6?$AA@; `string '
call_printf
addesp, 4

; 18 : n++;

movecx, DWORD PTR _n$[ebp]
addecx, 1
movDWORD PTR _n$[ebp], ecx

; 19 : }

jmpSHORT $L342
$L343:


借qhgary(Gary)的例子,while和if相比,while最后多了句
jmp SHORT $L342

[解决办法]
while = if+goto

读书人网 >C++

热点推荐