【问题标题】:Matching C++ code with C code将 C++ 代码与 C 代码匹配
【发布时间】:2014-01-10 16:40:19
【问题描述】:

我正在尝试掌握 C 代码。在这里,我试图用 C++ 中的代码复制 C 中的这段代码。或者更具体地说,我正在尝试使用 iostream 和 iomanip 而不是 printf 和 cstdio 将此代码从 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";
    }


}

除了 C++ 代码中的 10.0549 变为 10.055 之外,它看起来大部分是正确的。 知道我的 C++ 代码有什么问题吗?不过,由于我对 C 的理解还很陌生,因此可能会出现更多错误。

【问题讨论】:

  • 原始代码已经混合了典型的c 代码和c++??
  • 原代码是C++,不是C。
  • 输出精度的实现可能略有不同,或者您没有使用精确的等价物。
  • 原件的精度为 4 (%7.4f) 你用的精度为 5。
  • 对于给出的示例,原始“C”代码的 C++ 方面与 IMO 相当无关,因为它不会影响发布者所关注的输出。从技术上讲这是正确的,这不是 C。

标签: c++ c printf


【解决方案1】:

您想使用 std::fixed 和 4 的 setprecision 来复制 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 上查看 here for more info

【讨论】:

  • 虽然没有得到正确的输出。它给我的第一行是 而不是正确的 。虽然,它确实让最后一行正确。
  • 多哈。好的,现在应该修好了。 (没有双关语)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多