versoon 2016-02-03 01:46 采纳率: 66.7%
浏览 1484
已采纳

C++的简单静态变量问题

这道题是有关局部静态变量的使用,第一次调用函数返回0,以后每次被调用返回值增加1,
但是运行结果不合乎预期,请指教!
代码如下:
#include

using namespace std;

unsigned myCnt()
{
static unsigned iCnt = -1;
++iCnt;
return iCnt;
}

int main()
{
cout << "请输入任意字符后按回车键继续" << endl;
char ch;
while (cin >> ch)
{
cout << "函数myCnt()的执行次数是:" << myCnt << endl;

}
return 0;

}
运行情况却是:
图片说明

  • 写回答

1条回答

  • 林深 2016-02-03 01:50
    关注

    输出的地方是不是少加了括号? myCnt()

     #include "iostream"
    #include "cstdio"
    using namespace std;
    
    unsigned myCnt()
    {
        static unsigned iCnt = -1;
        ++iCnt;
        return iCnt;
    }
    int main()
    {
        cout << "请输入任意字符后按回车键继续" << endl;
        char ch;
        while (cin >> ch)
        {
            cout << "函数myCnt()的执行次数是:" << myCnt() << endl;
        }
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算