C ++ Измените printf на cout - PullRequest
       17

C ++ Измените printf на cout

0 голосов
/ 07 ноября 2019

У меня есть этот код ниже, который прекрасно работает. Мне просто нужно написать printf как cout. Я пробовал несколько раз, но это ошибки на мне. Любая помощь будет оценена.

#include <iostream>
#include <stdio.h>
using namespace std;

int main() {
    double mathScores[] = { 95, 87, 73, 82, 92, 84, 81, 76 };
    double chemScores[] = { 91, 85, 81, 90, 96, 89, 77, 79 };
    double aveScores[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
    //calculate size of array
    int len = sizeof(mathScores) / sizeof(double);
    //use array
    for (int i = 0; i < len; ++i) {
        aveScores[i] = (mathScores[i] + chemScores[i]) / 2;
    }
    printf("%s\t%s\t%s\t%s\n", "ID", "math", "chem", "ave");
    for (int i = 0; i < len; ++i) {
        printf("%d\t%.2f\t%.2f\t%.2f\n", i, mathScores[i], chemScores[i],
                aveScores[i]);
    }
    return 0;
}

Ответы [ 3 ]

1 голос
/ 07 ноября 2019

Библиотека iomanip включает методы для установки десятичной точности, а именно setprecision и fixed. Вы можете указать setprecision(2) и fixed для печати двух десятичных знаков как части каждого счета. Следующее выдает тот же вывод, что и исходный код.

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

int main() {
    double mathScores[] = { 95, 87, 73, 82, 92, 84, 81, 76 };
    double chemScores[] = { 91, 85, 81, 90, 96, 89, 77, 79 };
    double aveScores[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
    //calculate size of array
    int len = sizeof(mathScores) / sizeof(double);
    //use array
    for (int i = 0; i < len; ++i) {
        aveScores[i] = (mathScores[i] + chemScores[i]) / 2;
    }
    // Set decimal precision
    std::cout << std::setprecision(2);
    std::cout << std::fixed;
    std::cout << "ID\tmath\tchem\tave" << endl;
    for (int i = 0; i < len; ++i) {
        std::cout << i << "\t" << mathScores[i] << "\t" << chemScores[i] << "\t" << aveScores[i] << endl;
    }
    return 0;
}
0 голосов
/ 07 ноября 2019

Более знакомый синтаксис может быть достигнут с помощью Boost Library . Это будет выглядеть примерно так:

#include <iostream>
#include <stdio.h>
using boost::format
using namespace std;

int main() {
    double mathScores[] = { 95, 87, 73, 82, 92, 84, 81, 76 };
    double chemScores[] = { 91, 85, 81, 90, 96, 89, 77, 79 };
    double aveScores[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
    string s;
    char ss[30];
    //calculate size of array
    int len = sizeof(mathScores) / sizeof(double);
    //use array
    for (int i = 0; i < len; ++i) {
        aveScores[i] = (mathScores[i] + chemScores[i]) / 2;
    }

    cout<<format("%s\t%s\t%s\t%s\n") % "ID" % "math" % "chem" % "ave";
    //printf("%s\t%s\t%s\t%s\n", "ID", "math", "chem", "ave");
    for (int i = 0; i < len; ++i) {
        //printf("%d\t%.2f\t%.2f\t%.2f\n", i, mathScores[i], chemScores[i],
                aveScores[i]);
        cout<<format("%d\t%.2f\t%.2f\t%.2f\n") %i  % mathScores[i] % chemScores[i] % aveScores[i];
    }
    return 0;
}
0 голосов
/ 07 ноября 2019

Первая строка довольно проста, так как все это можно сделать одной строкой:

std::cout << "ID\tmath\tchem\tave" << std::endl;

однако, возможно, вы захотите обработать разделитель немного более явно:

const char TAB('\t');
std::cout << "ID" << TAB << "math" << TAB << "chem" << TAB "ave" << std::endl;

В цикле просто нужно использовать модификатор std::setprecision(), чтобы установить точность в двух местах:

for (int i = 0; i < len; ++i) {
    std::cout << std::setprecision(2)
              << i << TAB
              << mathScores[i] << TAB
              << chemScores[i] << TAB
              << aveScores[i] << std::endl;
}
...