我正在尝试编写一种方法来确定给定数字是否为 armstrong 数字。可以通过以下步骤找到 armstrong 号码:
- 取基数即 456 => 4, 5, 6
- 对位数的幂即456有3位,所以pow = 3
- 用 pow 为每个碱基供电,即 4^3、5^3、6^3
- 总和,即 64 + 125 + 216 = 405
如果总和等于原始数,则为 armstrong,即 405 != 456,因此不是 armstrong。
int armstrong(float number){ if(number < 1){ return 0; } else{ float *pointer = malloc(sizeof (float)), *temp; if(pointer == NULL){ printf("Error allocating memory: math::armstrong.\nReturn value 0."); return 0; } else{ int temp_boolean = 1, index = 0; float sum = 0, original_number = number; while(temp_boolean == 1){ if(number / 10 == 0){ temp_boolean = 0; } else{ temp = realloc(pointer, ((sizeof pointer / sizeof (float)) + 1) * sizeof (float)); pointer = temp; } pointer[index] = fmod(number, 10.0); //pointer[index] = number % 10; number /= 10; ++index; } int i; for(i = 0; i < index; ++i){ float temp_e = pointer[i]; sum += pow(temp_e, index); } free(pointer); if(sum == original_number){ return 1; } else{ return 0; } } }
如果给定的数字是 armstrong 数字,我的程序返回 1,否则返回 0。现在,当我将变量和参数作为 int 时,这工作正常,但我希望能够接收更大的数字,这就是为什么我的代码在 float 中有变量。但出于某种原因,它没有给出任何输出。它使用带有 -Wall 选项的 gcc 编译得很好,所以我不知道我做错了什么。
我正在使用 notepad++ 编写我的程序,并使用 gcc 进行编译。
最佳答案
float
类型的变量支持更大范围的值,但通过不代表范围内的每个可能值来实现这一点。例如,假设 float
的大小为 32 位,而 int
的大小为 32 位,则 int
可以表示一些整数值,但float
不能。
您的代码依赖于您所做的假设,即 float
可以表示每个整数值。如果该假设不正确 - 至少会有一些更大的整数值 - 您的函数将出现故障。
如果您希望您的函数适用于较大的值,请尝试找到一种表示较大整数值的方法(在超出内置类型可以表示的范围的意义上)。这样做有很多选择,但一种方法是传递 char
数组,其中数组中的每个元素代表一个整数(例如,0
-9
)。与此权衡的是,您需要在所选表示上模拟您使用的所有操作(除法、取模、求和、乘以 10 的幂等)。
关于c - 为什么我的程序不能使用 float 变量,但可以使用 int 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31984820/