#14471: 請問各位高手一個小問題


andy5202andy5202@gmail.com (子恆黃)


程式碼如下 請問輸出時(粗體字部分)是哪裡有錯 一直想不明白為何會多印出一堆數字 然而用for ( i = i - 1 ; i >= 0 ; i -- ) 來輸出就沒有問題 麻煩大家了
cout << s[i] ;

#include <iostream>

using namespace std ;

int main ()
{
int n , i ;
int s[1000] ;
while ( cin >> n )
{
s[1000] = 0 ;
i = 0 ;
while ( n > 0 )
{
s[i] = n % 2 ;
n /= 2 ;
i ++ ;
}
while ( i >= 0 )
{
cout << s[i-1] ;
i -- ;
}
cout << endl ;

}
}

#18107: Re:請問各位高手一個小問題


rexwu1104@gmail.com (黑雪公主 Black Lotus)


程式碼如下 請問輸出時(粗體字部分)是哪裡有錯 一直想不明白為何會多印出一堆數字 然而用for ( i = i - 1 ; i >= 0 ; i -- ) 來輸出就沒有問題 麻煩大家了
cout << s[i] ;

#include

using namespace std ;

int main ()
{
int n , i ;
int s[1000] ;
while ( cin >> n )
{
s[1000] = 0 ;<------------------------------------這邊全都是零
i = 0 ;                                                          ^
while ( n > 0 )                                               |
{                                                                  |
s[i] = n % 2 ;                                               |
n /= 2 ;                                                        |
i ++ ;<----------------------------你最後會多加一次
}
while ( i >= 0 )
{
cout << s[i-1] ;
i -- ;
}
cout << endl ;

}
}

所以會多輸出一個零