简体   繁体   English

一个读取整数的程序,只要它们交替正负。 C++

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

I'm new to programming in C++.我是 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 eg (2, -2, 2, -2, -2, -2).我不知道如何在if中不使用if来制作它,因此它可以读取例如 (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;
    }
}

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;
}

Also, you could use property (a XOR b) < 0 if a and b have a different sign bit.此外,如果ab具有不同的符号位,您可以使用属性(a XOR b) < 0

#include <iostream>

int main()
{
    int a, b;
    std::cin >> b;
    do {
        a = b;
        std::cin >> b;
    }while( (a^b) < 0);
    std::cout << "Same sign" << std::endl;
}
template<typename In, typename Out, typename F>
Out copy_while_alternative(In b, In e, Out r, F f)
{
    if (b == e) return r;
    
    bool lastF = f(*b);
    *r++ = *b++;
    while (b != e && f(*b) != lastF) {
        *r++ = *b++;
        lastF = !lastF;
    }
    return r;
}

https://godbolt.org/z/9rq93e https://godbolt.org/z/9rq93e

One possible implementation:一种可能的实现:

#include <iostream>

int main()
{
    int currentNumber, previousNumber;
    std::cin >> currentNumber;
    do
    {
        previousNumber = currentNumber;
        std::cin >> currentNumber;
    } while (currentNumber * previousNumber < 0);
}

Two numbers are opposite signs if their product is negative.如果它们的乘积为负,则两个数字的符号相反。

Move the first cin outside the loop将第一个 cin 移到循环外

int temp = 0, x = 0, y = 0;
cin >>x;
if ( x !=0)
{
    while (temp == 0){
//cin >> x;// should be above as this because it resets the +- order every 2nd time
        if (x > 0) {
            y = x;
            cin >> x;
            if (x < 0)
                continue;
            else if(y > 0 && x >= 0)//>= to avoid infinite loop if 0 is input
                break;
        }
        if(x < 0){
            y = x;
            cin >> x;
            if (x > 0) 
                continue;
            else if(y < 0 && x <= 0)//<= to avoid infinite loop if 0 is input
                break;
        }
    }
}

The other answers are already good, but I wanted to give a solution that is close to yours, to show you how you can simplify things.其他答案已经很好了,但我想提供一个与您的解决方案接近的解决方案,向您展示如何简化事情。

For example, you have a lot of unnecassary checks.例如,您有很多不必要的检查。 You test x < 0 , set y=x and then test y < 0 again.您测试x < 0 ,设置y=x ,然后再次测试y < 0

You were missing to consider the starting case separately.您没有单独考虑起始案例。 The cin >> x should not happen unconditionally every loop iteration. cin >> x不应在每次循环迭代时无条件地发生。

Here is a simplification:这是一个简化:

int x = 0;
int last = 0; //more meaningful name
cin >> last; //you were missing some starting point
while (true){ //you do not need temp, instead just replace it by what you want to say
    cin >> x;
    if (x > 0 && last < 0) {
        last = x;   
        continue;
    }
    else if(x < 0 && last > 0){
        last = x;
        continue;
    }
    break;
}

Of course it is somewhat better to replace these checks by a product check to simplify things even more.当然,最好用产品检查代替这些检查,以进一步简化事情。

If only the oposite sign is needed then number * -1 will do fine.如果只需要相反的符号,那么number * -1就可以了。

#include <iostream>
#include <string>

int main(){
    int input_int;
    std::string input;

    int last = 2;

    while (1){

        std::cout << "Last int -> " << last << std::endl;

        std::cin >> input;
        input_int = std::stoi(input);

        if (last * -1 == input_int) {
            last = input_int;
        } else {
            break;
        }

    }
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C++,计算正负数并计算数字的平均值)编写一个程序,读取未指定数量的整数 - C++ ,Count positive and negative numbers and compute the average of numbers) Write a program that reads an unspecified number of integers 如果 x 为正,我如何将 x 设置为负值,如果 x 为正,我如何将其设置为负。 c++ - How do i set x to be a negative value if x is positive, and if x is positive how do i set it to be negative. c++ 负整数和正整数之和导致意外输出 - C++ - Sum of negative and positive integers leads to unexpected output - c++ 编写一个读取五个整数并执行一些任务的C ++程序 - Writing a C++ program that reads five integers and performs a few tasks 在 C++ 中从二进制文件读取字节时,整数有时会偏离正数或负数 256 - Integers are sometimes off by positive or negative 256 when reading bytes from a binary file in C++ C++ 初学者 - 如何仅对用户输入的正整数或负整数求和以及如何计算平均值 - Beginner to C++ - How to sum up only positive or only negative integers the user inputs and how to calculate the avg C++ 负整数优化 - C++ Optimization on negative integers C ++中整数类型的正无穷大 - positive and negative infinity for integral types in c++ C ++ cin只有正整数 - C++ cin positive integers only C++ 只接受正整数 - C++ accepting positive integers only
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM