不理解while循环语法

时间:2015-03-20 05:41:03

标签: c++ loops while-loop

我需要输入驱动循环的帮助,这意味着用户输入两个值,并打印总和,差异,乘积,商和余数,直到用户为第二个值输入零。我不明白如何编写while循环我测试的变量

以下是一个示例:

enter two integers: 19 7
sum of 19 and 7 is 26
difference of 19 and 7 is 12 
etc..

4 个答案:

答案 0 :(得分:0)

我假设你是初学者......而你正在使用<iostream>。如果您正在使用其他内容,例如<cstdio>然后发表评论,我会更改代码,但它是这样的:(对于数字乘法,你可以弄清楚其余部分:D)

#include <iostream>
using namespace std;
int main (){
    int num1;
    int num2;
    while (true){
         cout << "Enter some numbers";
         cin >> num1 >> num2;
         cout << "Product is " << num1*num2;
    }
    return 0;
}

祝你好运!

答案 1 :(得分:0)

你可以尝试这样的事情。使用无限循环并根据自己的条件打破循环。

#include <iostream>
using namespace std;
int main (){
    int num1, num2;
    while (1){
         cout << "\nEnter some numbers ";
         cin >> num1 >> num2;
         if(num2==0)
               break;
         cout << "Product is " << num1*num2;
    }
    return 0;
}

答案 2 :(得分:0)

使用具有break条件的无限循环将起到作用。这是如何

#include<iostream>
int main()
  {
    int a , b;
    while( 1 )
      {
        std :: cout << "\nEnter two integers :" ;
        std :: cin >> a >> b ;
        if ( b == 0 )
           break;
        std :: cout << "\nSum of " << a << " and " << b << " is " << a + b ;
        std :: cout << "\nDifference of " << a << " and " << b << " is " << a - b ;
        std :: cout << "\nProduct of " << a << " and " << b << " is " << a * b ;
        std :: cout << "\nQuotient when " << a << " is divided by " << b << " is " << a / b ;
        std :: cout << "\nRemainder when " << a << " is divided by " << b << " is " << a % b ;
      }
    return 0;
  }

如果break,您只需使用b == 0即可。遇到break时,程序退出循环。 (如果你是一个总菜鸟并且不知道如何使用休息,请阅读break

while( 1 )是一个无限循环,程序只会在遇到break时退出循环。

还要记住,%不会在浮动上工作。如果你想要浮点数,那么你必须使用std::fmod()std :: fmod( a , b );返回余下的a除以b,其中a和{{1}是浮点数或双精度数,它包含在b头文件中。)

答案 3 :(得分:0)

这可以通过多种方式完成。例如

while ( true )
{
   std::cout << "Enter two integer numbers: ";

   int first;
   int second = 0;

   std::cin >> first >> second;

   if ( second == 0 ) break;

   std::cout << "sum of " << first 
                << " and " << second 
                << " is " << first + second;
                << std::endl;

   std::cout << "difference of " << first 
                << " and " << second 
                << " is " << first - second;
                << std::endl;

   // and other outputs if they are required
}
相关问题