首页 > 编程语言 > 详细

C++例题

时间:2020-01-22 17:02:50      阅读:71      评论:0      收藏:0      [点我收藏+]

1.整数反转输出

#include <iostream>
using namespace std;
int main()
{
    int n, _n, newname = 0;  // int取值范围:0 到 4294967295(232 - 1)
    cout << "请输入一个小于9位的数,我帮你输出倒数!" << endl;
    cin >>n;
    cout << n << "的倒数是:";
    do
    {
        _n = n % 10;
        n /= 10;
        cout << _n;
    } while (n!=0);
    cout << endl;
    return 0;
}

扩展:1000位以内的正整数的加法运算,见原文:https://zhidao.baidu.com/question/1820080074929553788.html

声明两个能容纳1000位十进制数的char型数组存储输入数字字符串,以长的做被加数和结果,短的长度控制加法循环次数。在加法过程中判断和处理进位。举例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//#include "stdafx.h"//If the vc++6.0, with this line.
#include "stdio.h"
#include "string.h"
int main(void){
    char a[1002]={‘0‘},b[1002]={‘0‘},*pl=a,*ps=b;
    int i,j,la,lb;
    while(1){//保证输入是正确的        
        printf("Input a & b(length<=1000)...\n");
        scanf("%[1234567890] %[1234567890]",a+1,b+1);//最前面留1位做进位
        if((la=strlen(a))<1002 && (lb=strlen(b))<1002)
            break;
        printf("Error, redo: ");
    }
    if(la<lb){//找出长的做被加数和结果
        ps=a,pl=b;
        j=la,la=lb,lb=j;
    }
    for(i=lb-1,j=la-1;i>0;i--,j--)//从末位向前对应加
        if((pl[j]+=ps[i]-‘0‘)>‘9‘)//某位>‘9‘则处理进位
            pl[j]-=10,pl[j-1]++;
    for(;j>0;j--)//若被加数有进位则继续做完
        if(pl[j]>‘9‘)
            pl[j]-=10,pl[j-1]++;
    printf("The result is %s\n",pl[0]==‘1‘ ? pl : pl+1);//有进位则第0位输出
    return 0;
}

2.星期

#include <iostream>
using namespace std;
int main()
{
    int day;
    cout << "请在1~7之间输入一个代表星期的数:(1:星期一;2:星期二;3:星期三;4:星期四;5:星期五;6:星期六;7:星期天)";
    cin >> day;
    switch (day)
    {
    case 1:
        cout << "星期一";
    case 2:
        cout << "星期二";
    case 3:
        cout << "星期三";
    case 4:
        cout << "星期四";
    case 5:
        cout << "星期五";
    case 6:
        cout << "星期六";
    case 7:
        cout << "星期天";
    default:
        break;
    }
}

C++例题

原文:https://www.cnblogs.com/qq2806933146xiaobai/p/12228804.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!