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. CallingAve(comp, bilang)triggers a division-by-zero error, which crashes the program before it can print any output. - Mismatched Loop Ranges: The
Countfunction usesi < gfor its loop, whileSum37usesi <= k. This creates inconsistency—if the upper bound is a valid number (e.g., 21, divisible by 3 and 7),Sum37will include it butCountwon't, leading to wrong average calculations. - Incorrect Output Text: The second line in the
displayfunction refers to a "sum" but should describe the average as per your requirement. - Integer Division Limitation: Using integer division in
Avewill 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
minandmaxto 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
doubleto preserve fractional values. - Safe Division: Added a check for zero count in the
Avefunction 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
相关产品推荐
相关产品推荐

