为什么模数运算符不适用于该代码

Why modulus operator does not work on that code?

本文关键字:适用于 代码 不适用 运算符 为什么      更新时间:2023-10-16
#include <iostream>
#include <string>
using namespace std;
int main() {
int n = 12;
int i, res;
string digits = to_string(n);

for(i = 0; i < digits.length(); i++){
res = 0;
res = n % digits[i];
if (res != 0){
res = false;
break;
}
if (res == 0){
res = true;
}
}

数字[0]是1,因此:12%1=0=res。然而,当我运行程序时,res=12,因此以下条件如果不能正常工作。怎么了?

感谢

digits[0]

包含字符'1',其数值为49。您正在评估12 % 49,它实际上是12。

如果要将数字字符转换为其值,可以像(digits[i] - '0')一样执行。

更改

res = n % digits[i];

res = n % (digits[i] - '0');

但前提是您确信digits将只包含数字字符。

ASCII字符代码可以通过谷歌搜索找到。这一页看起来不错。

https://www.asciitable.xyz/