不理解while循环语法

Dont understand while loop syntax

本文关键字:语法 循环 while 不理解      更新时间:2023-10-16

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

这是一个示例:

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

使用具有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;
  }

如果是b == 0,您只需要使用break。当遇到break时,程序将退出循环。(如果你是一个彻头彻尾的傻瓜,不知道如何使用break,请阅读此break)

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

还要记住,%在浮点运算中不起作用。如果需要浮点,则必须使用std::fmod()(当a除以b时,std :: fmod( a , b );返回余数,其中ab是浮点或双精度,它包含在<cmath>头文件中)。

我假设你是初学者。。。而您使用的是<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;
}

祝你的编码好运!

这可以通过多种方式实现。例如

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
}

您可以尝试这样的方法。使用一个无限循环,并根据自己的条件打破循环。

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