编程题#4:计算整数平方和(C++程序设计第10周)

来源:互联网 发布:杭州java培训机构 编辑:程序博客网 时间:2024/06/02 06:58

描述

下列程序每次读入一个整数N,若N为0则退出,否则输出N和N的平方。

#include <iostream>using namespace std;// 在此处补充你的代码int main(int argc, char* argv[]) {        CType obj;        int n;        cin>>n;        while ( n ) {                obj.setvalue(n);                cout<<obj++<<" "<<obj<<endl;                cin>>n;        }        return 0;}

输入

K个整数。除最后一个数据外,其他数据均不为0。

输出

K-1行。第I行输出第I个输入数和它的平方。

样例输入

1 5 8 9 0

样例输出

1 15 258 649 81

源码

#include <iostream>using namespace std;//在此处补充你的代码class CType{private:    int value;public:    CType():value(0) {};    void setvalue(int n)    {        value = n;    }    CType& operator ++ (int)    {//      static CType tmp = *this;//      static CType tmp = CType();//必须使用static变量,否则返回时内存就被释放了        static CType tmp;//必须使用static变量,否则返回时内存就被释放了        tmp.value = value;        value *= value;        return tmp;    }    friend ostream& operator << (ostream& o, CType& cType)//此处必须为友元函数    {        o << cType.value;        return o;    }};int main(int argc, char* argv[]){    CType obj;    int n;    cin >> n;    while(n)    {        obj.setvalue(n);        cout << obj++ << " " << obj << endl;        cin >> n;    }    return 0;}
0 0
原创粉丝点击