简体   繁体   English

std::cout 如何格式化 output?

[英]How does std::cout format the output?

How does std::cout work? std::cout 是如何工作的? The following code doesn't pass certain test cases for a question on HackerEarth.com:以下代码未通过有关 HackerEarth.com 问题的某些测试用例:

double n,a,b;
while(t--){
    cin>>n>>a>>b;
    long long x = round(b*n*1.0/(a+b));
    cout<<((a*x*x) + b*(n-x)*(n-x))<<endl;
}

while, the following one passes all of them:同时,以下一个通过了所有这些:

double n,a,b;
while(t--){
    cin>>n>>a>>b;
    long long x = round(b*n*1.0/(a+b));
    long long ans = (a*x*x) + b*(n-x)*(n-x);
    cout<<ans<<endl;
}

Why does it happen that when I store the calculated value in a variable, then only the test cases are passed?为什么会发生当我将计算值存储在变量中时,只有测试用例通过? Does the value change if directly printed to console?如果直接打印到控制台,值会改变吗? I am a newbie to C++.我是 C++ 的新手。

The output format "chosen" by cout (or any std::ostream ) depends on the type which is being outputted (specifically, it depends on the implementation of operator<< for that type). cout (或任何std::ostream )“选择”的 output 格式取决于输出的类型(具体而言,它取决于该类型的operator<<的实现)。

Let's look at what types are at play in both cases.让我们看看在这两种情况下都有哪些类型在起作用。

In your first example, you are outputting a double , since a , b , and n are doubles.在您的第一个示例中,您输出的是double精度数,因为abn是双精度数。 Even though x is a long long , the expression is a double due implicit conversions .尽管xlong long ,但由于 隐式转换,表达式是双重的。

In the second example, you are outputting a long long , since that is the type of ans .在第二个示例中,您输出的是long long ,因为那是ans的类型。 Note that your calculation of ans may be truncated, since it is being computed as a double (for the reasons explained above) but stored in a long long .请注意,您对ans的计算可能会被截断,因为它被计算为 double (出于上述原因)但存储在long long中。

Without knowing the details of the test cases you are talking about, one difference in the output is that doubles will likely be output in decimal notation (eg 1.23 or 1.0 ) whereas a long long (or any integral type) will be output as a whole number (note: there are ways to change this behavior, which I'm omitting here for simplicity). Without knowing the details of the test cases you are talking about, one difference in the output is that doubles will likely be output in decimal notation (eg 1.23 or 1.0 ) whereas a long long (or any integral type) will be output as a whole数字(注意:有一些方法可以改变这种行为,为了简单起见,我在这里省略了)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM