链接:登录—专业IT笔试面试备考平台_牛客网
来源:牛客网
Bessie is working with large numbers N (1 <= N <= 2,000,000,000) like 153920529 and realizes that the numbers would be a lot easier to read with commas inserted every three digits (as is normally done in the USA; some countries prefer to use periods every three digits). Thus, she would like to add commas: 153,920,529 . Please write a program that does this.
输入描述:
* Line 1: A single integer: N
输出描述:
* Line 1: The integer N with commas inserted before each set of three digits except the first digits (as traditionally done in many cultures)
示例1
输入
复制153920529
153920529
输出
复制153,920,529
153,920,529
我组代码如下:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
long long N; int a, b, c, d;
cin >> N;// N = ?,???,???,???
d = N % (int)1e3; //只取后三位
c = (N / (int)1e3) % 1000;//先取千及以上位的数,再只取后三位数
b = (N /(int)1e6) % 1000;//先取百万及以上位的数,再只取后三位的数
a = (N / 1e9);//只取最前一位
if (N >= 1 && N <= 999) //没有逗号
{
cout << d << endl;
}
else if (N < 1e6) //有一个逗号
{
cout << c << ',' << setw(3) << setfill('0') << d << endl;
}
else if (N < 1e9) //有两个逗号
{
cout << b
<< ',' << setw(3) << setfill('0') << c
<< ',' << setw(3) << setfill('0') << d << endl;
}
else if (N <= 2e9) //有三个逗号
{
cout << a
<< ',' << setw(3) << setfill('0') << b
<< ',' << setw(3) << setfill('0') << c
<< ',' << setw(3) << setfill('0') << d << endl;
}
return 0;
}
最后的结果是成功了,通过了所有测试用例。
这是我稍作修改后的代码,我组提交的代码中没有用到1e9等的写法而是直接写了很多零。
现在我使用了科学计数法,很显然编译器报错,说表达式必须具有整数或未区分范围的枚举类型。于是我将1e3,1e6都给强制转化为了int型,然而,我没有给最后的a的计算表达式中的1e9强制转化,但程序却意外地能正常运行,本人表示很不解。
请求诸位略做解答!