当前位置: 代码迷 >> 综合 >> C++练习(1001)——求a+b之和,且和数形式为三位一节,用逗号隔开。
  详细解决方案

C++练习(1001)——求a+b之和,且和数形式为三位一节,用逗号隔开。

热度:35   发布时间:2024-02-07 08:25:07.0

a,b为整形数据,输入两个数时用space键隔开,并以标准数字格式输出两数之和。

#include <iostream>
#include <string>
#include <sstream>using namespace std;string IntToString(int);int main()
{int a,b,c;string str;cout << "Input number a and b:";cin >> a >> b;c = a+b;cout << "a+b=" << c << endl;   // 对比用的str = IntToString(c);size_t len = str.length();for(int index =(int) len-3; index > 0; index -= 3)str.insert(index,",");cout << str << endl;        return 0;
}/* 将整形数据转变成字符串 */
string IntToString(int num)
{stringstream str;str << num;return str.str();
}

该练习的精髓有两步:
①将整型数据转换成字符串;
②将字符串视为一个对象,对齐进行操作。

记住:C++是一种面向对象的编程语言,程序中的变量都要将其视为对应一种类的对象,可对其进行属性观察和相应操作。