P8723 [蓝桥杯 2020 省 AB3] 乘法表

P8723 [蓝桥杯 2020 省 AB3] 乘法表

cpp 复制代码
#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <algorithm>
#include <format>
string toBaseP(int  n,int  p){//这里不要取引用,因为会改变值
  if(n == 0) return 0;
  string res = ""; 
  while(n){
    int mod = n %p;
     res += (mod < 0?mod + '0':mod -10 + 'A');
     n /=p;
  }
  reverse(res.begin(),res.end());
  return res;
 
}
int main(){
  int n;
  cin>>n;
  for(int i=1;i<=n-1;i++){
    for(int j =1;j<=i;j++){
      int a = i *j;
      cout<<format("{}*{}={} ",toBaseP(i,n),toBaseP(j,n),toBaseP(a,n));
      /*这里的 n 是通过引用传递的(int &n),意味着在函数内部修改 n 会直接改变调
      用时的实际参数值。这在转换进制的过程中会破坏原始的值,
      导致调用 toBaseP 后 i 和 j 的值被修改。 */
      //cout<<i<<"*"<<j<<"="<<a/n<<a%n<<" ";
    }
  cout<<endl;
  }
}

C++ 中允许将字符和整数直接进行算术运算,这是因为字符在底层被存储为整数(ASCII 值)。通过这种特性,简单的数学运算就可以实现字符和数字的转换。

相关推荐
MicroTech20252 小时前
MLGO微算法科技发布突破性运动想象脑机接口算法,高精度与低复杂度兼得
科技·算法
cici158742 小时前
基于不同算法的数字图像修复Matlab实现
算法·计算机视觉·matlab
Savior`L9 小时前
二分算法及常见用法
数据结构·c++·算法
mmz120710 小时前
前缀和问题(c++)
c++·算法·图论
努力学算法的蒟蒻10 小时前
day27(12.7)——leetcode面试经典150
算法·leetcode·面试
甄心爱学习11 小时前
CSP认证 备考(python)
数据结构·python·算法·动态规划
kyle~11 小时前
排序---常用排序算法汇总
数据结构·算法·排序算法
AndrewHZ12 小时前
【遥感图像入门】DEM数据处理核心算法与Python实操指南
图像处理·python·算法·dem·高程数据·遥感图像·差值算法
CoderYanger12 小时前
动态规划算法-子序列问题(数组中不连续的一段):28.摆动序列
java·算法·leetcode·动态规划·1024程序员节