C++程序不断读取用户的整数,直到两个连续输入数字之和大于或等于10



我正在尝试解决问题,但没有得到所需的输出。C++程序不断读取用户的整数,直到两个连续输入数字之和大于或等于10。则程序将输出所有正输入数的和。

#include<iostream>
using namespace std;
int main( )
{
int num_1, num_2, result=0;
int i;
int results=0;
cout << "Enter the value : ";
cin >> num_1;
cout << "Enter the value : ";
cin >> num_2;
if (num_1 > 0 && num_2 > 0)
{
results = num_1 + num_2;
}

do
{   
if (results <= 10)
{
for(i=0;i<=result;i++)
{
cout << "Enter the value : ";
cin >> num_1;
cout << "Enter the value : ";
cin >> num_2;

result = num_1 + num_2+results ;
cout << "Result = " << result;
cout << endl;
}
}
}
while (result <= 10);
system("pause");
return 0;
}

您可以通过几个简单的步骤来解决问题,而不需要多个循环。

给你:

#include <iostream>
int main( )
{
int sum_of_all_positive_nums { };
bool isLessThan { };
std::cout << "Enter the value: ";
int num_1;
std::cin >> num_1;
if ( num_1 > 0 ) { sum_of_all_positive_nums += num_1; }
do
{
std::cout << "Enter the value: ";
int num_2;
std::cin >> num_2;
const int sumOfTwoNums { num_1 + num_2 };
isLessThan = ( sumOfTwoNums < 10 ) ? true : false;
if ( num_2 > 0 ) { sum_of_all_positive_nums += num_2; }
if ( isLessThan ) { std::cout << "nRepeat!n"; num_1 = num_2; }
} while ( isLessThan );
std::cout << "nSum of all positive numbers == "
<< sum_of_all_positive_nums << 'n';
std::cin.get( );
}

样本输入/输出:

Enter the value: -2
Enter the value: 3
Repeat!
Enter the value: 4
Repeat!
Enter the value: 5
Repeat!
Enter the value: 5
Sum of all positive numbers == 17

几个重要注意事项:

  1. 请勿在全局范围内使用using namespace std;
  2. 不要在一条语句中声明多个变量
  3. 不要使用system("pause");等特定于平台的功能

最新更新