The following two programs, one written in C++ and the other written in C, both accept input from stdin that consists of the names of cars and the miles per gallon achieved by 3 drivers for those cars on a hypothetical test course. The programs print out the car with the best gas mileage. For example, given the input:
camry 23 17 28 g20 30 32 27 prius 48 38 41 f150 15 18 20 malibu 18 23 14they produce (roughly) the output:
prius 42.3333In the C program I have commented and highlighted the statements that differ from the C++ version.
#include <iostream> #include <string> using namespace std; // auto turns out to be a C++ reserved word so I substituted car instead class car { public: string name; float avg_mpg; }; // it's better to declare constants rather than hard-coding them const int NUM_DRIVERS = 3; main() { car max_car; // holds the car with the best gas mileage seen thus far float avg; // average gas mileage for the current car int mpg[NUM_DRIVERS]; // gas mileage achieved by drivers for current car string model; // name of current car // initialize max_car.avg_mpg to a small value or else it might never get set max_car.avg_mpg = -1.0; while (cin >> model >> mpg[0] >> mpg[1] >> mpg[2]) { // remember to cast either the numerator or divisor to a float in order // to avoid integer arithmetic avg = (mpg[0] + mpg[1] + mpg[2]) / (float)NUM_DRIVERS; if (avg > max_car.avg_mpg) { max_car.name = model; max_car.avg_mpg = avg; } } cout << "best car = " << max_car.name << endl; cout << "mpg = " << max_car.avg_mpg << endl; }
// the header files are different in C #include <stdio.h> #include <string.h> #include <stdlib.h> // auto turns out to be a C reserved word so I substituted car instead struct car { // C uses structs rather than classes char name[100]; // C represents strings using char arrays float avg_mpg; }; // it's better to declare constants rather than hard-coding them but you // may have to use #define rather than const #define NUM_DRIVERS 3 main() { struct car max_car; // holds the car with the best gas mileage seen thus far float avg; // average gas mileage for the current car int mpg[NUM_DRIVERS]; // gas mileage achieved by drivers for current car char model[100]; // name of current car // initialize max_car.avg_mpg to a small value or else it might never get set max_car.avg_mpg = -1.0; // must use scanf rather than cin to read from stdin while (scanf("%s %d %d %d", model, &mpg[0], &mpg[1], &mpg[2]) != EOF) { // remember to cast either the numerator or divisor to a float in order // to avoid integer arithmetic avg = (mpg[0] + mpg[1] + mpg[2]) / (float)NUM_DRIVERS; if (avg > max_car.avg_mpg) { // need to use strcpy rather than assignment operator (=) to assign // strings from one variable to another strcpy(max_car.name, model); max_car.avg_mpg = avg; } } // use printf rather than cout to print to stdout printf("best car = %s\n", max_car.name); printf("mpg = %f\n", max_car.avg_mpg); }