ADCChannel Constructor Validation

#include <iostream>
using namespace std;

class ADCChannel {
private:
    int channel;
    int resolution;

public:
    // Constructor with validation logic
    ADCChannel(int ch, int res) {
        // Validate Channel: Range 0 to 15
        if (ch < 0) {
            channel = 0;
        } else if (ch > 15) {
            channel = 15;
        } else {
            channel = ch;
        }

        // Validate Resolution: Must be 8, 10, or 12
        if (res == 8 || res == 10 || res == 12) {
            resolution = res;
        } else {
            // Default safe value if input is invalid
            resolution = 12;
        }
    }

    // Method to display the internal state
    void print() {
        cout << "CH=" << channel << " RES=" << resolution << endl;
    }
};

int main() {
    int ch, res;
    // Get user input for channel and resolution
    if (!(cin >> ch >> res)) return 0;

    // Create the object; validation happens immediately
    ADCChannel adc(ch, res);
    
    // Output the results
    adc.print();

    return 0;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Input

3 10

Expected Output

CH=3 RES=10