注册 登录
编程论坛 C语言论坛

抄了一个打印设定上下范围的所有整数的平方和程序!

visor 发布于 2022-04-20 18:39, 1191 次点击
#include <stdio.h>
#include <stdbool.h>

long get_long(void);
bool bad_limits(long begin, long end, long low, long high);
double sum_squares(long a, long b);

int main(void) {
    const long MIN = -10000000L;
    const long MAX = +10000000L;
    long start;
    long stop;

    double answer;

    printf("This program computes the sum of the squares of"
           "integers in a range.\nThe lower bound should not"
           "be less than -10000000 and\nthe upper bound"
           "should not be more than +10000000.\nEnter the"
           "limits (enter 0 for both limits to quit);\n"
           "lower limit: ");
    start = get_long();
    printf("upper limit: ");
    stop = get_long();
    while (start != 0 || stop != 0) {
        if (bad_limits(start, stop, MIN, MAX))
            printf("please try again.\n");
        else {
            answer = sum_squares(start, stop);
            printf("The sum of the square of the integers ");
            printf("from %ld to %ld is %g\n", start, stop, answer);
        }
        printf("Enter the limits(enter 0 for both limits to quit):\n");
        printf("lower limit: ");
        start = get_long();
        printf("upper limit: ");
        stop = get_long();
    }
    printf("Done!.\n");
    return 0;
}

long get_long(void) {
    long input;
    char ch;

    while (scanf("%ld", &input) != 1) {
        while ((ch = getchar()) != '\n')
            putchar(ch);
        printf(" is not an integer.\nplease enter an ");
        printf("integer value,such as 25,-178,or 3: ");
    }
    return input;
}

bool bad_limits(long begin, long end, long low, long high) {
    bool not_good = false;
    if (begin > end) {
        printf("%ld isn't smaller than %ld .\n", begin, end);
        not_good = true;
    }
    if (begin < low || end < low) {
        printf("Values must be %ld or greater.\n", low);
        not_good = true;
    }
    if (begin > high || end > high) {
        printf("Values must be %ld or less", high);
        not_good = true;
    }
    return not_good;
}

double sum_squares(long a, long b) {
    double total = 0;
    long i;

    for (i = a; i <= b; i++)
        total += (double)i * (double)i;

    return total;
}

[此贴子已经被作者于2022-4-20 18:40编辑过]

4 回复
#2
rjsp2022-04-21 09:09
平方和公式是 n(n+1)(2n+1)/6
-10000000L到+10000000L的平方和 = 2 * 10000000*(10000000+1)*(2*10000000+1)/6 = 666666766666670000000
ln(666666766666670000000)/ln(2) = 70bits
而 double 的有效位才区区 53bits
当然,如果你说不求结果准确,那当我没说
#3
visor2022-04-21 10:49
你这是高手啊,我是初学者,没有研究这么深啊。不过我看书上写double一般是64位?到底是多少位?
#4
rjsp2022-04-21 11:07
double占用64bits,有效位只有53bits

1bit的符号位,11bits的阶码,隐含的1.不占空间,52bits的尾数
所以,double的有效位是53bits
#5
visor2022-04-21 11:54
谢谢,
1