任务:
在 N 个元素的数组中 (N < 20) of the unsigned long long type find the maximal full square and print its index (starting from zero). If there are no full squares, print -1. If there is more than one maximal square, print the index of the first one.
输入数据:标准输入流,其中 N写在第一行 第二行是带有空格的数组元素。
输出数据:标准输出流中的数字
代码:
#include <stdio.h>
#include <math.h>
int main() {
unsigned short int n;
unsigned long long mass[20];
unsigned long long max = 0;
int max_index = -1;
scanf("%hu", &n);
if (n >= 20) {
do{
scanf("%hu", &n);
}while(n >= 20);
}
for (int i = 0; i < n; i++) {
scanf("%llu", &mass[i]);
long double root = (long double) sqrt(mass[i]);
if (root * root == mass[i]) {
if (mass[i] > max) {
max = mass[i];
max_index = i;
}
}
}
printf("%d\n", max_index);
return 0;
}
我编译时遇到这个错误
我尝试使用不同类型的数据,但没有用。
至少有这些问题:
编译器错误
错误消息表明 OP 正在使用 C++ 编译器,而应使用 C 编译器。
精度损失
sqrt(mass[i])
可能会失去精度。 unsigned long long
至少是 64 位类型,将其转换为 double
(以执行平方根)可能会丢失精度。对于整数问题,使用整数数学比使用浮点数学更好。
类似问题
root * root == mass[i]
考虑形成
unsigned long isqrt_ull(unsigned long long x)
来求平方根。
您使用的是较旧版本的 Microsoft 编译器。我无法在我拥有的版本中重现您的编译器错误。
但是你可以而且应该改变这一点:
long double root = (long double) sqrt(mass[i]);
if (root * root == mass[i]) {
对此:
double value = (double)mass[i];
double root = sqrt(value);
if (root * root == value) {
转换回 long double 不会给你带来任何好处。并且
mass[i]
形式 unsigned long long 到 double 的显式转换可能会修复您的编译器错误。