将C++代码与 C 代码匹配

Matching C++ code with C code

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

>我正在尝试掌握C代码。在这里,我尝试用 C 语言复制此代码,并使用 C++ 中的代码。或者更具体地说,我正在尝试使用 iostream 和 iomanip 而不是 printf 和 csdio 将此代码从 printf 转换为 cout。

//C CODE 
#include <cstdio> 
#include <cstdlib> 
using namespace std; 
int main() { 
 string header_text = "Basic IO"; 
 srand(0); 
 printf("%-10s::n", header_text.c_str()); 
 for (int i=0; i<4; i++) { 
 int number1 = rand()%1000; 
 float number2 = (float)number1/91.0; 
 printf("<%3d, %7.4f>n", number1, number2); 
 } 
 printf("n");
}

现在我想把它转换为C++。

这是我的尝试:

//C++ code
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
int main() {
    string header_text = "Basic IO";
    srand(0);
    cout << setw(10) << left << header_text << "::n";
    for (int i=0; i <4; i++) {
        int number1 = rand()%1000;
        float number2 = (float)number1/91.0;
        cout << "<" <<number1 <<setw(3) << ","   <<setw(7) << setprecision(5)  << number2  << ">n";
    }

}

看起来它基本上是正确的,除了 10.0549 在C++代码中变成 10.055。知道我的C++代码有什么问题吗?虽然,它可能还有更多错误,因为我对理解 C 仍然很陌生。

你想使用 std::fixed 和 setprecision 4 来复制 printf 的%.4f

cout << ... << fixed << setprecision(4)  << number2  << ">n";

输出:

Basic IO  ::
<383,  4.2088 >
<886,  9.7363 >
<777,  8.5385 >
<915,  10.0549>

有关 std::setprecision 和 std::fixed 的更多信息,请参阅此处。