C++:输入输出,字符串,命名空间

1.输出斐波那契数列的前20项

#include <iostream>

using namespace std;

int main()
{
    int a[20];
    int i;
    for(i=0;i<20;i++)
    {
        if(i<2)
        {
            a[i]=1;
            cout<<a[i]<<ends;
        }
        else
        {
            a[i]=a[i-1]+a[i-2];
            cout<<a[i]<<ends;
        }
    }

    return 0;
}

2.输入一个字符,判断该字符是大写还是小写,如果是大写字母,则转变成对应的小写字母输出,如果是小写字母,则转变成对应的大写字母输出,如果是其他字符,则转变成 '*' 并输出.

#include <iostream>

using namespace std;

int main()
{
    char ch;
    cout<<"请输入一个字符:";
    cin >> ch;
    if('a'<ch && ch<'z')
    {
        ch=ch-32;
        cout <<"ch= "<<ch<<endl;
    }
    else if('A'<ch && ch<'z')
    {
        ch=ch+32;
        cout<<"ch=" <<ch<<endl;
    }
    else
    {
        ch=42;
        cout<<"ch="<<ch<<endl;
    }
    return 0;
}

3.输入一个字符串,统计该字符串中字母、数字、空格、其他字符的个数并输出

#include <iostream>

using namespace std;

int main()
{
     string str;
    cout<<"请输入一串字符:";

    getline(cin,str);

    int  num=0,ch=0,kong=0,other=0;
    int t=str.size();
    for(int i=0;i<t;i++)
    {
        if(str.at(i)>=48 && str.at(i)<=57)
        {
            num=num+1;
        }
        else if((str.at(i)>=65 && str.at(i)<=90) || (str.at(i)>=97 && str.at(i)<=122) )
        {
            ch=ch+1;
        }
        else if(str.at(i)==' ')
        {
                kong=kong+1;
        }
        else
        {
            other=other+1;
        }
    }

    cout<<"字母个数:"<<ch<<endl;
     cout<<"数字个数:"<<num<<endl;
      cout<<"空格个数:"<<kong<<endl;
       cout<<"其他字符个数:"<<other<<endl;
    return 0;
}

4. 命名空间

#include <iostream>

using namespace std;

namespace N1
{
    int num = 100;
    double score = 90.0;
    char value = 'a';
}


namespace N2
{
    int key = 60;
    int num = 50;
}

using namespace N1;
using namespace N2;

int key=66;

int main()
{

     cout << N1::num << endl;
     cout << N2::num << endl;

     cout << N2::key << endl;
     cout << ::key << endl;

     char value = 'z';
     cout<<N1::value<<endl;

     cout<<value<<endl;



    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值