c ++中的平方数,Kaprekar数 [英] Squaring number in c++, Kaprekar numbers

查看:298
本文介绍了c ++中的平方数,Kaprekar数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中发现这个问题,同时检测范围内的Kaprekar数字。对于数字77778 -

Found this issue in C++ while detecting Kaprekar numbers in a range. For number 77778 -

unsigned long long sq = pow(n, 2);

返回6,049,417,284,而

returns 6,049,417,284 while

unsigned long long sq = n * n;

返回1,754,449,988

returns 1,754,449,988

这是一种溢出,pow避免,但正常n * n不。

Any ideas why? Is this some sort of overflow which pow avoids but normal n*n does not.

推荐答案

假设您的 n 是典型的 int unsigned int ,原因是因为

Assuming your n to be typical int or unsigned int, the reason for this is because

p>

this line

unsigned long long sq = n * n;

相当于

unsigned long long sq = (int)(n * n);

,因为在将结果分配给sq之前,n * n将首先处理(均为整数)。因此,这是一个溢出问题(欢迎来到 Stack Overflow )!

as the n * n will be first processed (both as integers) before assigning the result to sq. So, this is an overflow problem (And welcome to Stack Overflow too!).

您也可能想要了解这些术语 overflow casting 更多通过搜索(因为他们是非常常见的问题,在计算,早期了解他们将是很大的帮助!)。

You also probably want to understand these terms overflow and casting more by searching around (since they are very common issues in Computing, understanding them early will be of great help!).

这与Kaprekar数字无关。在大多数现在的机器 int 是32位。因此,它只能处理值-2,147,483,648到2,147,483,647(或0到4,294,967,295无符号整数计数器部分)。

This has nothing to do with Kaprekar numbers. In most of nowadays machine int is 32-bit. Thus it can only handle value -2,147,483,648 to 2,147,483,647 (or 0 to 4,294,967,295 for unsigned integer counter part).

因此,处理n * n会为您提供:

Thus processing n * n will give you:

n * n = 6,049,417,284 - 4,294,967,296 = 1,754,449,988 //overflow at (4,294,967,295 + 1)!

如果您之前投放:

unsigned int n = 77778;
unsigned long long sq = pow(n, 2);
unsigned long long sq2 = (unsigned long long)n * n; //note the casting here.
std::cout << sq << std::endl;
std::cout << sq2 << std::endl;

然后结果将是相同的,因为不会有溢出

Then the results will be identical, since there won't be overflow.

这篇关于c ++中的平方数,Kaprekar数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆