[英]C++ ,Count positive and negative numbers and compute the average of numbers) Write a program that reads an unspecified number of integers
[英]A program that reads integers as long as they are alternately positive and negative. C++
我是 C++ 编程新手。 我一直在尝试创建一个读取整数的程序,只要它们交替正负。 我不知道如何在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;
}
}
我会读取循环外的第一个数字,并根据该数字是正数还是负数设置一个变量。 然后我会让循环读取数字,并根据变量知道是期待正数还是负数。 如果它得到它所期望的,反转变量中的值,然后重复。 在一些伪代码中,按照这个一般顺序:
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;
}
此外,如果a
和b
具有不同的符号位,您可以使用属性(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;
}
一种可能的实现:
#include <iostream>
int main()
{
int currentNumber, previousNumber;
std::cin >> currentNumber;
do
{
previousNumber = currentNumber;
std::cin >> currentNumber;
} while (currentNumber * previousNumber < 0);
}
如果它们的乘积为负,则两个数字的符号相反。
将第一个 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;
}
}
}
其他答案已经很好了,但我想提供一个与您的解决方案接近的解决方案,向您展示如何简化事情。
例如,您有很多不必要的检查。 您测试x < 0
,设置y=x
,然后再次测试y < 0
。
您没有单独考虑起始案例。 cin >> x
不应在每次循环迭代时无条件地发生。
这是一个简化:
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;
}
当然,最好用产品检查代替这些检查,以进一步简化事情。
如果只需要相反的符号,那么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.