You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++程序函数输出异常问题:求指定范围内数的和与平均值

Fixing Your C++ Program Issues

Let's break down why your program fails to output results when inputting 4 and 12, and fix all the underlying problems step by step:

Key Problems in the Original Code

  • Division by Zero Crash: When there are no numbers divisible by both 3 and 7 (like in the 4-12 range), the bilang (count variable) becomes 0. Calling Ave(comp, bilang) triggers a division-by-zero error, which crashes the program before it can print any output.
  • Mismatched Loop Ranges: The Count function uses i < g for its loop, while Sum37 uses i <= k. This creates inconsistency—if the upper bound is a valid number (e.g., 21, divisible by 3 and 7), Sum37 will include it but Count won't, leading to wrong average calculations.
  • Incorrect Output Text: The second line in the display function refers to a "sum" but should describe the average as per your requirement.
  • Integer Division Limitation: Using integer division in Ave will truncate decimal values. For example, if the sum is 63 and count is 2, integer division would give 31 instead of the correct 31.5.

Corrected Code

#include <iostream>
#include <iomanip> // For decimal precision formatting
using namespace std;

// Calculate sum of numbers divisible by both 4 and 6 (simplified to divisible by LCM 12)
int Sum46(int a, int b) {
    int sum = 0;
    // Ensure we iterate from smaller to larger number, regardless of input order
    int start = min(a, b);
    int end = max(a, b);
    for (int i = start; i <= end; i++) {
        if (i % 12 == 0) {
            sum += i;
        }
    }
    return sum;
}

// Calculate sum of numbers divisible by both 3 and 7 (simplified to divisible by LCM 21)
int Sum37(int a, int b) {
    int sum1 = 0;
    int start = min(a, b);
    int end = max(a, b);
    for (int i = start; i <= end; i++) {
        if (i % 21 == 0) {
            sum1 += i;
        }
    }
    return sum1;
}

// Count numbers divisible by both 3 and 7 (fixed loop condition to match Sum37)
int Count(int a, int b) {
    int inputCount = 0;
    int start = min(a, b);
    int end = max(a, b);
    for (int i = start; i <= end; i++) {
        if (i % 21 == 0) {
            inputCount++;
        }
    }
    return inputCount;
}

// Calculate average with safe division and decimal support
double Ave(int totalSum, int count) {
    if (count == 0) {
        return 0.0; // Avoid division by zero when no valid numbers exist
    }
    return static_cast<double>(totalSum) / count;
}

// Display results with correct descriptive text
void display(int sum46, double ave37) {
    cout << "The sum of all integers that are both divisible by 4 and 6 between two numbers is " << sum46 << endl;
    cout << fixed << setprecision(2); // Optional: format average to 2 decimal places
    cout << "The average of all integers that are both divisible by 3 and 7 between two numbers is " << ave37 << endl;
}

int main() {
    int num1, num2;
    int probA;
    double probB;
    int sum37, count37;

    cout << "Input first number : ";
    cin >> num1;
    cout << "Input second number : ";
    cin >> num2;

    probA = Sum46(num1, num2);
    sum37 = Sum37(num1, num2);
    count37 = Count(num1, num2);
    probB = Ave(sum37, count37);

    display(probA, probB);

    return 0;
}

Additional Improvements

  • Input Order Handling: Added min and max to ensure loops always run from the smaller to larger number, even if the user enters values in reverse order.
  • Simplified Divisibility Checks: Used least common multiples (LCM) to streamline the conditions (divisible by 12 = divisible by 4 and 6; divisible by 21 = divisible by 3 and 7).
  • Decimal Average Support: Changed the average return type to double to preserve fractional values.
  • Safe Division: Added a check for zero count in the Ave function to prevent crashes.

Test Result for Input 4 and 12

Input first number : 4
Input second number : 12
The sum of all integers that are both divisible by 4 and 6 between two numbers is 12
The average of all integers that are both divisible by 3 and 7 between two numbers is 0.00

内容的提问来源于stack exchange,提问作者Space Monkey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:13:14