将C++代码与 C 代码匹配
Matching C++ code with C code
>我正在尝试掌握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 的更多信息,请参阅此处。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 为什么我的代码在输出中增加了93天
- 我的简单if-else语句是如何无法访问的代码
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 为什么在这个代码结束循环中没有得到结束
- 在c代码之间共享数据的最佳方式
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值