C++将printf更改为cout

C++ Change printf to cout

本文关键字:cout printf C++      更新时间:2023-10-16

下面的代码非常有效。我只需要把印刷品写成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("%st%st%st%sn", "ID", "math", "chem", "ave");
for (int i = 0; i < len; ++i) {
printf("%dt%.2ft%.2ft%.2fn", i, mathScores[i], chemScores[i],
aveScores[i]);
}
return 0;
}

iomanip库包括设置小数精度的方法,即setprecisionfixed。您可以指定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 << "IDtmathtchemtave" << endl;
for (int i = 0; i < len; ++i) {
std::cout << i << "t" << mathScores[i] << "t" << chemScores[i] << "t" << aveScores[i] << endl;
}
return 0;
}

第一行非常简单,因为它可以作为一个字符串完成:

std::cout << "IDtmathtchemtave" << 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;
}

使用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("%st%st%st%sn") % "ID" % "math" % "chem" % "ave";
//printf("%st%st%st%sn", "ID", "math", "chem", "ave");
for (int i = 0; i < len; ++i) {
//printf("%dt%.2ft%.2ft%.2fn", i, mathScores[i], chemScores[i],
aveScores[i]);
cout<<format("%dt%.2ft%.2ft%.2fn") %i  % mathScores[i] % chemScores[i] % aveScores[i];
}
return 0;
}