2017-02-01 4 views
-1

Это домашнее задание, которое требует использования указателей для вывода сообщений, когда входное значение делится на 3, на 5 и на 3 & 5. Код компилируется и запускается, но я не получаю желаемый результат. Кроме того, я не уверен, что нужно изменить. Вот мой код:Проблемы с выпуском с использованием указателей для ветвления и циклирования на C++?

#include <iostream> 
#include <iomanip> 

using namespace std; 
using std::istream; 

int main() 
{ 
    const int i{3};      // Variable initialization and declaration 
    long* pnumber{};      // Pointer definition and initialization 
    long number1 {};      // Declaration and initialization of variable number1 
    long number2 [i];     // Declaration and initialization of variable containing array of 3L numbers 
    char indicator{ 'n' };    // Continue or not? 

    pnumber = &number1;     // Store address in a pointer 

    for (;;) 
    { 
     cout << "Please enter any number less than 2 billion, " 
      << "then press the Enter key: "; 
     cin >> number1; 

     if (*pnumber % 3 == 0)   // Test if remainder after dividing by 3 is 0 
     { 
      cout << endl 
       << "Number: " << number1 
       << "-Fizz" << endl 
       << endl << "Do you want to enter another value (please enter y or n? "; 
      cin >> indicator;   // Read indicator 
      if (('n' == indicator) || ('N' == indicator)) 
       break;     // Exit from loop 
     } 

     if (*pnumber % 5 == 0)   // Test if remainder after dividing by 5 is 0 
     { 
      cout << endl 
       << "Number: " << number1 
       << "-Buzz" << endl 
       << endl << "Do you want to enter another value (please enter y or n? "; 
      cin >> indicator;   // Read indicator 
      if (('n' == indicator) || ('N' == indicator)) 
       break;    // Exit from loop 
     } 

     if ((*pnumber % 3 == 0) && (*pnumber % 5 == 0)) // Test if remainder after dividing by 5 and 3 is 0 
     { 
      cout << endl 
       << "Number: " << number1 
       << "-FizzBuzz" << endl 
       << endl << "Do you want to enter another value (please enter y or n? "; 
      cin >> indicator;   // Read indicator 
      if (('n' == indicator) || ('N' == indicator)) 
       break;    // Exit from loop 
     } 

     else 
     { 
      cout << endl    // Default: here if not divisible by 3 or 5 
       << "Please enter another number." 


       << endl << "Do you want to enter another value (please enter y or n? "; 
      cin >> indicator;   // Read indicator 
      if (('n' == indicator) || ('N' == indicator)) 
       break;    // Exit from loop 
     } 
    } 

    pnumber = &number2 [i];    // Change pointer to address of number2 

    for (;;) 
    { 
     cout << endl << endl 
      << "Please enter an array of number(s), where the number is less than 2 billion, " 
      << "then press the Enter key: "; 
     cin >> number2 [i]; 

     if (*pnumber % 3 == 0)   // Test if remainder after dividing by 3 is 0 
     { 
      cout << endl 
       << "Number: " << number2 
       << "-Fizz" << endl 
       << endl << "Do you want to enter another array (please enter y or n? "; 
      cin >> indicator;   // Read indicator 
      if (('n' == indicator) || ('N' == indicator)) 
       break;     // Exit from loop 
     } 

     if (*pnumber % 5 == 0)   // Test if remainder after dividing by 5 is 0 
     { 
      cout << endl 
       << "Number: " << number2 
       << "-Buzz" << endl 
       << endl << "Do you want to enter another array (please enter y or n? "; 
      cin >> indicator;   // Read indicator 
      if (('n' == indicator) || ('N' == indicator)) 
       break;    // Exit from loop 
     } 

     if ((*pnumber % 3 == 0) && (*pnumber % 5 == 0)) // Test if remainder after dividing by 5 and 3 is 0 
     { 
      cout << endl 
       << "Number: " << number2 
       << "-FizzBuzz" << endl 
       << endl << "Do you want to enter another value (please enter y or n? "; 
      cin >> indicator;   // Read indicator 
      if (('n' == indicator) || ('N' == indicator)) 
       break;    // Exit from loop 
     } 

     else 
     { 
      cout << endl    // Default: here if not divisible by 3 or 5 
       << "Please enter another number." 


       << endl << "Do you want to enter another value (please enter y or n? "; 
      cin >> indicator;   // Read indicator 
      if (('n' == indicator) || ('N' == indicator)) 
       break;    // Exit from loop 
     } 
    } 

    cout << endl; 
    return 0; 
} 
+0

Так что же * ошибка * именно вы получаете? Взгляните на этот пост о некоторых предложениях при обращении за помощью к домашним заданиям: https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions – sas

+0

Проблема заключается в том, номер 2 выводится во второй части кода при вводе нескольких номеров. Он выводит Number: 008FFA88-Fizz, а не если я ввел 6, он должен вывести Number: 6-Fizz. – phoenixCoder

+0

Почему 'using std :: istream' с' using namespace std'? – Raindrop7

ответ

0

С вашего собственного Я мог бы понять, что вы хотите напечатать Fizz, когда вход полностью делится на 3, печать Buzz, когда вход полностью делится на 5 и печати FizzBuzz когда его делимой по 3 и 5 обе. Теперь, если мое предположение верно, чем вы делаете логическую ошибку здесь. Я поясню пример.

Допустим, что входной номер 30. Ваша программа будет делиться на 3, чтобы она напечатала Fizz, а затем она найдет, что она делится на 5, поэтому она также напечатает Buzz. И в конце по той же причине он также напечатает FizzBuzz. Пока вы хотели напечатать только FizzBuzz.

Вот как вы должны решить эту проблему.

 // First check if it is divisible by both 3 and 5 ? 
    if ((*pnumber % 3 == 0) && (*pnumber % 5 == 0)) // Test if remainder after dividing by 5 and 3 is 0 
    { 
     cout << endl 
      << "Number: " << number2 
      << "-FizzBuzz" << endl 
      << endl << "Do you want to enter another value (please enter y or n? "; 
     cin >> indicator;   // Read indicator 
     if (('n' == indicator) || ('N' == indicator)) 
      break;    // Exit from loop 
    } 
    // if not, then is it divisible by 3 only ? 
    else if (*pnumber % 3 == 0)   // Test if remainder after dividing by 3 is 0 
    { 
     cout << endl 
      << "Number: " << number2 
      << "-Fizz" << endl 
      << endl << "Do you want to enter another array (please enter y or n? "; 
     cin >> indicator;   // Read indicator 
     if (('n' == indicator) || ('N' == indicator)) 
      break;     // Exit from loop 
    } 
    // if not, then is it divisible by 5 only? 
    else if (*pnumber % 5 == 0)   // Test if remainder after dividing by 5 is 0 
    { 
     cout << endl 
      << "Number: " << number2 
      << "-Buzz" << endl 
      << endl << "Do you want to enter another array (please enter y or n? "; 
     cin >> indicator;   // Read indicator 
     if (('n' == indicator) || ('N' == indicator)) 
      break;    // Exit from loop 
    } 
    // everything else ... 
    else 
    { 
     cout << endl    // Default: here if not divisible by 3 or 5 
      << "Please enter another number." 


      << endl << "Do you want to enter another value (please enter y or n? "; 
     cin >> indicator;   // Read indicator 
     if (('n' == indicator) || ('N' == indicator)) 
      break;    // Exit from loop 
    } 
+0

Теперь проблема заключается в выводе номер 2 во второй части кода при вводе нескольких номеров. Он выводит Number: 008FFA88-Fizz, а не если я ввел 6, он должен вывести Number: 6-Fizz. – phoenixCoder

+0

Это потому, что вы неправильно присваиваете массив целых чисел указателю 'pnumber'. Посмотрите на https://www.programiz.com/cpp-programming/pointers-arrays для лучшего понимания обработки массива с помощью указателей. – Roshan

+0

Я попытался использовать & number2 без [i], но он выдает ошибку. – phoenixCoder