算法学习之顺序结构

套路:

读入数据
计算结果
打印输出

案例一

题目:输入一个三位数,分离出它的百位、十位和个位,反转后输出。
样例输入:127
样例输出:721

分析:首先将三位数读入变量n,然后进行分离。百位等于n/100,十位等于n/10%10(这里的%是取余数操作),
个位等于n%10。
程序如下:

#include <conio.h>
#include<stdio.h>
int main(){
    int n;
    scanf("%d",&n);
    printf("%d%d%d
",n%10,n/10%10,n/100);
    getch();
    return 0;
}


继续改造,

#include <conio.h>
#include<stdio.h>
int main(){
    int n,m;
    scanf("%d",&n);
    m = (n%10)*100 + (n/10%10)*10 + (n/100);
    printf("%3d
",m);//表示占据3个位置 
    printf("%03d
",m);//表示占据3个位置,空白以0填补,前面填补空白 
    printf("%04d
",m);//表示占据4个位置,空白以0填补 
    getch();
    return 0;
}


案例二

题目:输入两个整数a和b,交换二者的值,然后输出。
样例输入:824 16
样例输出:16 824
分析:这个就不多说了,太经典了

代码:

#include <conio.h>
#include<stdio.h>
int main(){
    int a,b,t;
    scanf("%d",&a);
    scanf("%d",&b);
    t = a;
    a = b;
    b = t;
    printf("%d
%d",a,b); 
    getch();
    return 0;
}

输入也可以像下面的代码一样来写

#include <conio.h>
#include<stdio.h>
int main(){
    int a,b,t;
    scanf("%d%d",&a,&b);//可以用空格来区分两个变量,或者用enter键来区分 
    t = a;
    a = b;
    b = t;
    printf("%d %d
",a,b); 
    getch();
    return 0;
}

如果说效果呢?下面的程序更直接,兼职无语

#include <conio.h>
#include<stdio.h>
int main(){
    int a,b,t;
    scanf("%d%d",&a,&b);//可以用空格来区分两个变量,或者用enter键来区分 
    printf("%d %d
",b,a); 
    getch();
    return 0;
}

实现了输入的两个数对调,但实际上,两个变量值未改变!只能说,很贱很无敌。

这些只是小例子,

说明了顺序结构编程的特点,就是一直往下走。一直走。直到处理完成。

原文地址:https://www.cnblogs.com/jiqing9006/p/3188775.html