(c language) Is there a way to reduce the coding that I planned?

Asked 1 years ago, Updated 1 years ago, 330 views

Coding is successful, but... I was wondering if I'd been coding too long. The coding got longer. We're going to separate the smaller, the larger of the two intervention values. I was wondering if there was a simple way. Please give me a map^

^

The goal I'm trying to implement = Take two integers and output the sum and average (avg) of the numbers from small to large, multiples of 3 or 5.

Implementation Results-

Input - 1015

Output -

sum = 37

avg = 12.3

The coding that I made

int b,c;
int sum = 0, cnt = 0;
double avg;

scanf_s("%d %d", &b, &c);
if(b<c){
for (b; b <= c; b++) {
    if (b % 3 == 0 || b % 5 == 0) {
        sum += b;
        cnt++;
    }
}
}
else if (b > c) {
for (c; c <= b; c++) {
    if (c % 3 == 0 || c % 5 == 0) {
        sum += c;
        cnt++;
    }
}
}
avg = (double)sum / cnt;
printf("sum = %d\n", sum);
printf("avg = %.1f\n", avg);

c

2022-10-26 00:00

1 Answers

How about comparing the values of b and c and adding a small number to start and a large number to end The start and end values are assigned differently than the start and else if to create only one code for the loop.

Additional) Of course, even if the code gets longer, it would be better to find a multiple of 3, a multiple of 5, and a multiple of 15, respectively, and then do a multiple of 3 + a multiple of 5 - a multiple of 15. This is because the % operation is time consuming. (To obtain a multiple of n, find the smallest multiple of n in water equal to or greater than start in % operation, and then add n to that number.)


2022-10-26 00:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.