为什么这两个输出不同?

时间:2021-02-05 14:18:25

标签: c++ c++17

我是否使用 scanf 而不是 cin 具有相同的数字 (999999999.1) 结果不同。 为什么?

// code 1 
#include <bits/stdc++.h>
using namespace std; 
int main() {
    double n; 
    cin >> n;  
    printf("%f\n",ceil(n));  
    cout << ceil(n); 
}   
// code 2
#include <bits/stdc++.h>
using namespace std; 
int main() {
    double n; 
    scanf("%f",&n); 
    printf("%f\n",ceil(n));  
    cout << ceil(n); 
}   

1 个答案:

答案 0 :(得分:2)

    scanf("%f",&n); 

错了。 %f 用于阅读 float。您应该使用 %lf 来阅读 double

double 的打印可以通过 %f 完成)