C++判断两数倍数代码报expression must have integral错误如何解决
错误产生原因
报错出在给r1、r2赋值的两行代码,核心是语法使用错误:
<<是C++标准输出流cout的专属插入运算符,不能直接用来拼接整数和字符串生成std::string对象- 编译器遇到
n1 << "is a multiple of "的写法时,会把<<识别为整数的位左移运算符,该运算符要求右侧操作数必须是整数或无范围枚举类型,你传入了字符串常量,因此触发「expression must have integral or unscoped enum type」报错。
另外你原代码没有引入<string>头文件,即使修复了上述问题,用到std::string时也会触发隐式声明相关的报错。
修复方案
两种改法都符合你作业要求使用条件运算符的规则:
方案1:直接在条件运算符内输出(逻辑最简单)
不需要提前把结果存为字符串变量,直接通过条件运算符选择输出内容即可:
#include <iostream> #include <string> using namespace std; int main() { int n1; int n2; cout << "Enter a number: \n"; cin >> n1; cout << "Enter another number:\n"; cin >> n2; int residue = n1 % n2; bool isMultiple = residue == 0; isMultiple ? cout << n1 << " is a multiple of " << n2 : cout << n1 << " is not a multiple of " << n2; return 0; }
方案2:先拼接字符串再输出(匹配你原代码的写法逻辑)
如果需要先把结果存到string变量中再输出,需要先把整数用to_string()方法转成字符串类型,再用+做字符串拼接:
#include <iostream> #include <string> using namespace std; int main() { int n1; int n2; cout << "Enter a number: \n"; cin >> n1; cout << "Enter another number:\n"; cin >> n2; int residue = n1 % n2; bool isMultiple = residue == 0; string r1 = to_string(n1) + " is a multiple of " + to_string(n2); string r2 = to_string(n1) + " is not a multiple of " + to_string(n2); string ans = isMultiple ? r1 : r2; cout << ans; return 0; }
内容的提问来源于stack exchange,提问作者Santiago Uribe Gil
相关产品推荐
相关产品推荐

