2016-02-19 3 views
-4

В настоящее время я работаю над программой, которая выводит число 1089 (т. Е. Магическое число) трехзначного целого числа, первая цифра которого больше его последней. У меня есть код, набравший код, но я не получаю 1089, вместо этого я получаю 891. Может ли кто-нибудь объяснить какое-то объяснение.Объяснение кода C++

//Uses a cout to inform user will be using the number 412 as an example. 
     //Uses a cout to explain to user the number needs to be reversed. 
     cout << "Alright, let's walk through an example, using the number 412." << endl; 
     int numExample = 412; 
     cout << "Please input 412" << endl; 
     cin >> numExample; 
     cout << "First, the number 412 is reversed." << endl; 
     //The following is done for reversing the number 412: 
      int reverseNum = 0, remainder = 0; 
      while (numExample) 
      { 
       remainder = numExample % 10; 
       reverseNum = (reverseNum * 10) + remainder; 
       numExample = numExample/10; 
      } 
       cout << "The reverse of 412 is " << reverseNum << endl; 
     cout << "Next, we want to subtract the reverse of the original number from its reverse" << endl; 
     cout << "This gives us 198" << endl; 
     cout << "From there, we want to reverse 198." << endl; 
     //The same procedure is used to reverse 198 
     int numExample2 = 198; 
     cout << "Please enter 198" << endl; 
     cin >> numExample2; 
      int reverseNum2 = 0, remainder2 = 0; 
      while (numExample2) 
      { 
       remainder2 = numExample2 % 10; 
       reverseNum2 = (reverseNum2 * 10) + remainder2; 
       numExample2 = numExample2/10; 
      } 
     cout << "The reverse of 198 is " << reverseNum2 << endl; 
     int magicNumber = (reverseNum2 + numExample2); 
     cout << "Following that, we want to add 891 to 189 which gives us " << magicNumber << endl; 
+1

Подсказка: каково значение 'numExample2' после цикла while (numExample2)? (Если вы этого не знаете, распечатайте его.) – molbdnilo

+0

Я считаю, что я определил его выше, но 'numExample2' является int равным 198. –

+1

Действительно? Добавьте 'cout << numExample2 << endl;' сразу после печати 'reverseNum2'. И подумайте немного о том, что заставляет цикл закончить. – molbdnilo

ответ

0

Попробуйте написать функцию, чтобы справиться с этим, так что ваш код чище (Это также облегчит для людей, чтобы помочь вам!)

#include <iostream> 
#include <cmath> 
using namespace std; 

int reverseDigit(int num); // For example purposes 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    int Number1, 
    Number2, 
    temp1, 
    temp2, 
    Result; 

    cout << "Enter the number 412: "; 
    cin >> Number1; 

    temp1 = reverseDigit(Number1); 

    temp1 = Number1 - temp1; 

    cout << "Enter the number 198: "; 
    cin >> Number2; 

    temp2 = reverseDigit(Number2); 

    Result = temp1 + temp2; 

    cout << "The magic number is: " << Result << endl; 

    return 0; 
} 

int reverseDigit(int num) 
{ 
    int reverseNum = 0; 
    bool isNegative = false; 

    if (num < 0) 
    { 
     num = -num; 
     isNegative = true; 
    } 

    while (num > 0) 
    { 
     reverseNum = reverseNum * 10 + num % 10; 
     num = num/10; 
    } 

    if (isNegative) 
    { 
     reverseNum = -reverseNum; 
    } 

    return reverseNum; 
} 

Я понимаю, что вы не работаете с негативов так вы можете удалить этот бит, если вы решили использовать его, вы также можете расширить его ... Говоря это, это сделает реальный «процесс реверсирования» более удобным для работы и улучшения и чтения.

+0

@molbdnilo Или просто сделайте это лучше, и напишите функцию, чтобы вы не заблудились в своей работе! (ПОЖАЛУЙСТА, ОБРАТИТЕ ВНИМАНИЕ: использование вами и вашим является общим и не нацелено на вас лично, но на любого, кто читает комментарий ..) – suroh

Смежные вопросы