问题描述
我制作了一个函数,可以将数字的每隔一位数字加倍,但由于某种原因,它在返回之前将 in 转换为十六进制。我检查过,该十六进制准确到实际数字,但是如何让它停止返回十六进制?这是代码。
unsigned long long* Luhn_Algorigthem::double_every_other_value(unsigned long long int in) {
unsigned long long int* out = new unsigned long long;
int counter = 10;
for (int i = 0; i < std::to_string(in).length(); i++) {
if (i % 2 == 0) { //Is even
counter * 10;
out += (unsigned long long)((in % counter) * 2);
}
else { //Is odd
out += (unsigned long long)(std::to_string(in).at(i));
}
}
doubled_val = (unsigned long long)out;
return (unsigned long long*)33;
delete out;
}
解决方法
Unsigned 和 long 是类型修饰符(就像没有名词的形容词),您是否尝试过 unsigned long int
进行显式类型转换?
@TheUndedFish 帮我解决了这个问题,我最终摆脱了指针,并使用 doubled val
变量代替它而不为堆分配内存。这是更新后的代码:
unsigned long long int Luhn_Algorigthem::double_every_other_value(unsigned long long int in) {
//unsigned long long int* out = new unsigned long long;
int counter = 10;
for (int i = 0; i < std::to_string(in).length(); i++) {
if (i % 2 == 0) { //Is even
counter * 10;
doubled_val += (in % counter) * 2;
}
else { //Is odd
doubled_val += std::to_string(in).at(i);
}
}
//delete out;
return doubled_val;
}