Указатели Домашнее задание - PullRequest
0 голосов
/ 22 марта 2012

Если кто-нибудь может помочь мне закончить это и указать, что нужно было сделать, чтобы программа работала, это было бы здорово.

-спросите, сколько дней пользователь хочет ввести с 1-365 (проверить)

-спросить температуру для каждого дня между -60 и 90 градусов по Цельсию (цикл, проверить)

-конвертировать каждое значение в градусы Фаренгейта (функция)

-выходрезультаты (функция)

Задача

- пользователи должны ввести целое число целого числа, целое число, но оно преобразуется в двойное число Фаренгейта, например.4 по Цельсию преобразуется в 39,20 по Фаренгейту

  • для этого кода ...

    cout << "Температура по Цельсию для Дня" << i + 1 << ":";</p>

    * (days + 1) = GetValidInt ("", TEMP_MIN, TEMP_MAX);

выводит и ждет ввода на новой строке ... какя могу заставить его ждать ввода на той же строке?

    #include <IOSTREAM> // input/outout stream
    #include <IOMANIP>  // for setw manipulator
    #include <CFLOAT>   // for limits of a double DBL_MIN and DBL_MAX
    #include <CLIMITS>  // for limits of a int INT_MIN and INT_MAX

    using namespace std;

    //Function Prototypes
    double GetValidDouble(string prompt = "", const double MIN = DBL_MIN, const double MAX = DBL_MAX);
    int GetValidInt(string prompt = "", const int MIN = INT_MIN, const int MAX = INT_MAX);
    int outputFunc (int*);
    double calcCelsius(double*);
    int main() {
            //Constants
            const int TEMP_MIN = -90;
            const int TEMP_MAX = 60;
            const int DAYS_MIN = 1;
            const int DAYS_MAX = 365;
            //Pointer
            int numDays;
            int *days;
            //Determine the number of days to get input for
            //Validation - Must be numeric || Between 1 - 365
            numDays = GetValidInt("How many days do you wish to enter? ", DAYS_MIN, DAYS_MAX);

            //Array Allocation
            cout << "TEMPRETURE REPORTER" << endl;
            cout << "====================" << endl;
            cout << "Please enter the tempreture for each day." << endl;
            try{
                    days = new int[numDays];
                        for(int i = 0; i < numDays; i++){
                            cout << "Celsius temperature for Day " << i+1 << " : ";
                            *(days + 1) = GetValidInt("", TEMP_MIN, TEMP_MAX);
                            //Validation - Between -90.00C and 60.00C
                        }
                        //for loop
                        for(int i = 0; i < numDays; i++){
                                cout << "" << outputFunc(&days);
                              }
                        //output function
                    delete[] days;
                }
            catch(bad_alloc){
                    cout << "\nCould not allocate that amount memory.";
                }
            cout << endl << endl;
            system("pause");
            return 0;
            }
            //An inline function is a function upon which the compiler has been requested to perform inline expansion. 
            //In other words, the programmer has requested that the compiler insert the complete body of the function 
            //in every place that the function is called, rather than generating code to call the function in the one place it is defined.
            inline double calcCelsius(double* celsius){
                double fahrenheit = 0;
                fahrenheit = (celsius*9/5)+32;
                return fahrenheit;
            }
            //Output Function
            int outputFunc (int* days){
                double fahrenheit = 0;
                //PROCESS
                //double     //&days int
                fahrenheit = calcCelsius(&days); //Calling calcCelsius
                //OUTPUT
                cout << right << setw(15) << "Day " << numDays << setw(10) << fahrenheit << char(248) << "F" << setw(10) << numDays << char(248) << "C" << endl;
            }
            double GetValidDouble(string prompt, const double MIN, const double MAX){
               double validNumber = 0.0; // holds the user input
               string rubbish;           // holds garbage input.

               cout << endl << prompt << " "; 
               cin >> validNumber;       // try to get input
               if(cin.fail()){           // if user input fails...
                   cin.clear();              // reset the cin object
                   cin >> rubbish;           // cleans garbage from cin.

                   // report the problem to the user.
                   cerr << "\nInvalid input. Please try again and enter a numeric value.\n";
                   // Try again by calling the function again (recursion)
                   validNumber = GetValidDouble(prompt, MIN, MAX);
               } 
               else if(validNumber < MIN || validNumber > MAX){// if value is outside range...
                   // report the problem to the user.
                   cerr << "\nInvalid input. Please try again and enter a value between "
                        << MIN << " and " << MAX << ".\n";
                   // Try again by call the function again (recursion)
                   validNumber = GetValidDouble(prompt, MIN, MAX);
               }
               return validNumber; // returns a valid value to the calling function.
            }
            int GetValidInt(string prompt, const int MIN, const int MAX){
                   double validNumber = 0.0; // holds the user input
                   validNumber = GetValidDouble(prompt, MIN, MAX); // get a number
                   if((int) validNumber < validNumber) // if the value is not a whole number...
                   {
                       cerr << "\nInvalid input. Please try again and enter a whole number.\n";
                       // Try again by calling the function again (recursion)
                       validNumber = GetValidInt(prompt, MIN, MAX);
                   }
                   return (int) validNumber; // returns a valid value to the calling function.
            }

Ответы [ 3 ]

1 голос
/ 22 марта 2012

Ваша проблема в этой строке:

cout << endl << prompt << " ";

в getValidDouble. Он выводит символ новой строки перед получением значения от пользователя, после , когда вы выводите свой собственный запрос.

Почему вы на самом деле не используете параметр prompt для запроса чего-либо? Это очевидно по причине: -)

Таким образом, он будет выведен после новой строки, и ваш ввод будет в той же строке. Другими словами, что-то вроде изменения:

cout << "Celsius temperature for Day " << i+1 << " : ";
*(days + 1) = GetValidInt("", TEMP_MIN, TEMP_MAX);

в

#include <sstream>
:
std::stringstream ss;
ss << "Celsius temperature for Day " << (i+1) << " : ";
*(days + 1) = GetValidInt (ss.str(), TEMP_MIN, TEMP_MAX);

Это должно исправить вашу непосредственную проблему, перевод строки после приглашения. У вас также есть некоторые другие проблемы, такие как передача неправильных типов данных в функции, но я оставлю их на ваше усмотрение, поскольку это сделает вас лучшим программистом. Один совет, скомпилируйте с предупреждениями и прочитайте то, что говорит вам компилятор.

1 голос
/ 22 марта 2012

Вы выводите разрыв строки перед запросом числа:

  cout << endl << prompt << " ";  // Output a line break ????
  cin >> validNumber;       // try to get i

Просто удалите первую строку выше.

0 голосов
/ 23 марта 2012

ПОПРОБУЙТЕ, и я имею в виду попробовать, xcode не помечает никаких ошибок, но у него нет времени, чтобы запустить и отладить его, это (очевидно, это не завершено, просто вырезайте и вставляйте его поверх своей)

    //Function Prototypes
double GetValidDouble(string prompt = "", const double MIN = DBL_MIN, const double MAX = DBL_MAX);
int GetValidInt(string prompt = "", const int MIN = INT_MIN, const int MAX = INT_MAX);
void outputFunc (int*,int);
double calcCelsius(double*);
int main() {
    //Constants
    const int TEMP_MIN = -90;
    const int TEMP_MAX = 60;
    const int DAYS_MIN = 1;
    const int DAYS_MAX = 365;
    //Pointer
    int numDays;
    int *days;
    //Determine the number of days to get input for
    numDays = GetValidInt("How many days do you wish to enter? ", DAYS_MIN, DAYS_MAX);  //Validation - Must be numeric || Between 1 - 365

    //Array Allocation
    cout << "TEMPRETURE REPORTER" << endl;
    cout << "====================" << endl;
    cout << "Please enter the tempreture for each day." << endl;
    try{
        days = new int[numDays];
        for(int i = 0; i < numDays; i++){
            string prompt = "Celsius temperature for Day "  + (i+1);
            *(days + 1) = GetValidInt(prompt, TEMP_MIN, TEMP_MAX); //Validation - Between TEMP_MIN and TEMP_MAX
        }
        //for loop
        for(int i = 1; i < numDays; i++){
            cout << "" ;
            outputFunc(days,i);  //we send the whole array
        }
        //output function
        delete[] days;
    }
    catch(bad_alloc){
        cout << "\nCould not allocate that amount memory.";
    }
    cout << endl << endl;
    system("pause");
    return 0;
}
//An inline function is a function upon which the compiler has been requested to perform inline expansion. 
//In other words, the programmer has requested that the compiler insert the complete body of the function 
//in every place that the function is called, rather than generating code to call the function in the one place it is defined.
inline double calcCelsius(int celsius){
    return (celsius*9/5)+32; //parentheses not really needed
}
//Output Function
void outputFunc (int* days, int a){
    int temp = days[a];
    cout << right << setw(15) << "Day " << a << setw(10) << calcCelsius(temp) << char(248) << "F" << setw(10) << &days << char(248) << "C" << endl;
}

Я ничего не изменил. Я не знаю, действительно ли это то, что вам нужно, я имею в виду, что оно выполнит работу (вероятно) или, по крайней мере, с несколькими изменениями. Но я не знаю, должен ли ты использовать что-то конкретное.

Основные изменения:

  • OutputFunc теперь недействителен и содержит в себе. Вы можете сделать это или он возвращает std :: string и выводит это. Но вы не можете иметь это вернуть int и вывести его внутри (ну, вы можете, но это не то, что тебе нужно здесь).
  • newDay вне контекста в outputFunc, поэтому вам нужно пройти это. Но в любом случае это счетчик, который вам нужно отправить.

  • calcCelcius (который я назвал deg2far или celc2far) теперь возвращает double и принимает int (все еще в строке)

  • Помните, что вы храните значения в i + 1 (начиная с 0) поэтому ваше первое значение в днях [1] ... цикл вывода должен начаться в 1.

Могут быть и другие изменения (очевидно, прототип для функций), но это основные.

Я не совсем уверен, сработает ли строка 54 string prompt = "Celsius temperature for Day " + (i+1);, может быть, вам нужно объявить это отдельно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...