Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

A program that reads integers as long as they are alternately positive and negative. C++

I'm new to programming in C++. I've been trying to create a program that reads integers as long as they are alternately positive and negative. I don't know how to make it without using if in if, and because of that it can read e.g (2, -2, 2, -2, -2, -2).

int temp = 0, x = 0, y = 0;
while (temp == 0){
    cin >> x;
    if (x > 0) {
        y = x;
        cin >> x;
        if (x < 0)
            continue;
        else if(y > 0 && x > 0)
            break;
    }
    if(x < 0){
        y = x;
        cin >> x;
        if (x > 0) 
            continue;
        else if(y < 0 && x < 0)
            break;
    }
}
question from:https://stackoverflow.com/questions/65889080/a-program-that-reads-integers-as-long-as-they-are-alternately-positive-and-negat

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would read the first number outside the loop, and set a variable based on whether that number is positive or negative. Then I'd have the loop read numbers, and based on the variable know whether to expect a positive or negative number. If it gets what it expects, invert the value in the variable, and repeat. In something pseudo-codeish, something on this general order:

read(number)

// if this number's negative, expect the next to be positive (and vice versa)
expect_positive = number < 0

for (;;) {
    read(number)
    bool positive = number >= 0
    if (positive != expect_positive)
        break;
    expect_positive = !expect_positive;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...