算法入门(1)

本文介绍了几个基本算法的实现,包括数字的反转输出、三个整数的排序、水仙花数的查找及倒三角形的绘制。这些算法对于初学者理解编程逻辑和流程控制非常有帮助。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在学习算法,所以想把所写的程序记录下来,程序比较简单,但是我相信始终会有帮助的

输入一个三位数,分离出它的百位,十位和个位,反转后输出

#include <stdio.h>
#include <iostream>
using namespace std;
int main(){
      int n;
      scanf("%d", &n);
      if (n%10==0)
      {
            printf("%d%d\n", n / 10 % 10, n /100);
      }
      else
      {
            printf("%d%d%d\n", n % 10, n / 10 % 10, n /100);
      }
      system("pause");
      return 0;
}

输入三个整数,从小到大输出

#include <stdio.h>
#include <iostream>
using namespace std;
void comparethree(int &a, int &b, int &c);
int main(){
      int a,b,c,t;
      scanf("%d%d%d", &a,&b,&c);
      comparethree(a, b, c);
      printf("%d\t%d\t%d\n", a, b, c);
      system("pause");
      return 0;
}

void comparethree(int &a, int &b, int &c){
      int t;
      if (a>b)
      {
            t = a;
            a = b;
            b = t;
      }
      if (a>c)
      {
            t = a;
            a = c;
            c = t;
      }
      if (b > c){
            t = b;
            b = c;
            c = t;
      }
}

水仙花数
输出100-999中所有的水仙花数。若3位数ABC 满足ABC = A3+B3+C3,则称其为水仙花数。

#include <stdio.h>
#include <iostream>
using namespace std;
int main(){
      for (int i = 1; i <= 9; i++)
      {
            for (int j = 0; j <= 9; j++){
                  for (int z = 0; z <=9; z++)
                  {
                        int x = i*i*i;
                        int y = j*j*j;
                        int m = z*z*z;
                        int s = i * 100 + j * 10 + z;
                        if (s==x+y+m)
                        {
                              printf("%d\n", s);
                        }
                  }
            }
      }
      system("pause");
      return 0;
}

倒三角形
输入正整数,输出一个n层的倒三角形,例如n=5时输出如下:

#########
 #######
  #####
   ###
    #

#include <stdio.h>
#include <iostream>
using namespace std;
int main(){
      int n;
      int count = 0;
      scanf("%d", &n);  //输入层数
      for (int i = n; i >=1; i--)  从顶层开始
      {
            int s = 1 + 2 * (i - 1); //等差数列求得#数量
            count++;
            for (int j = 0; j < s; j++)
            {
                  printf("#");
            }
            printf("\n");
            for (int x = 0; x < count; x++)
            {
                  printf(" ");  //用于打印空格
            }

      }
      system("pause");
      return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值