我下面的代码非常有效。我只需要将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;
}
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;
}
第一行非常容易,因为它们都可以作为一个字符串完成:
Boost Library可以实现更熟悉的语法。它看起来像这样: