2016-10-05 12 views
0

数字の桁がすべて奇数であるかどうかをチェックするプログラムを作ろうとしていますが、数字が奇数桁からのみであることを示すcoutは、 1桁の長さ。ここ は、コードは次のとおりです。数字の奇数を確認する

int main() 
{ 
    int n, c; 
    cin >> n; 
    while (n != 0) { 
     c = n % 10; 
     if (c % 2 == 1) { 
      n = n/10; 
      if (n == 0) { 
       cout << " Number has only odd digits"; 
      } 
     } 
     else 
      cout << " Number doesn't have only odd digits"; 
     return 0; 
    } 
} 
+3

インデントを整理してください –

+5

デバッガを使用してコードを1行ずつ進めてください。問題は非常に明白になるはずです。 –

+0

どのような混乱.... – nosbor

答えて

0

私は奇妙な数字の文字列を検索する、その後、文字列として数を維持するお勧めします。

static const char odd_digits[] = "13579"; 
std::string number_as_text; 
std::cin >> number_as_text; 
std::string::size_type position; 
position = number_as_text.find_first_of(odd_digits); 
if (position != std::string::npos) 
{ 
    std::cout << "Number has at least one odd digit.\n"; 
} 

数、文字列として、任意の文字から検索され奇数桁のリスト

0

私は、あなたの元の思考の流れを保つために、最小限の変更を加えました。 n=n/10else件の場合に実行する必要があります。 input as 0のケースの追加が追加されました。偶数桁を検出したときにreturn(0)文が追加されました(継続するポイントがないため、そこから戻されます)。

int main() {  
    int n, c; 
    cin >> n; 

    if (n==0) { 
     cout << "Number is zero. So it doesn't have only odd digits" << endl; 
     return(0); 
    } 

    while (n != 0) { 
     c = n % 10; n = n/10;  
     cout << "n=" << n << " c=" << c << endl; 

     if (c % 2 == 1) { 
      if (n == 0) { 
       cout << "Number has only odd digits" << endl; 
      } 
     } 
     else { 
      cout << "Number doesn't have only odd digits" << endl; 
      return(0); 
     } 
    } 
    return(0); 
} 
0

あなたの問題は、これらの行です:コンパイラは、このように解釈される

else 
    cout << " Number doesn't have only odd digits"; 
    return 0; 

それは関係なく、常に cが奇数か偶数かの returnを実行していることを意味
else { 
    cout << " Number doesn't have only odd digits"; 
} 
return 0; 

。この問題を解決するには、あなたのelse節への明示的な括弧を追加します。ほとんどのスタイルガイドは、常にifelse後にカッコを使用する必要がなぜ

else { 
    cout << " Number doesn't have only odd digits"; 
    return 0; 
} 

この種のエラーは、唯一のラインがあっても、です。

+0

また、['goto fail;'](https://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an)としても知られています。 -unofficial-patch /)のバグです。 –

関連する問題