不理解while循环语法
Dont understand while loop syntax
我需要输入驱动循环的帮助,这意味着用户输入两个值,并打印和、差、积、商和余数,直到用户为第二个值输入零。我不知道如何编写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 );
返回余数,其中a
和b
是浮点或双精度,它包含在<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;
}
相关文章:
- C 表示循环语法理解
- 如何使用 c++11 语法创建 for 循环以遍历向量
- 带有迭代器语法与发电机语法的循环
- 循环语法C++奇怪
- 奇怪的语法错误在基于范围的循环中报告
- 此 for 循环语句的正确语法
- GCC 4.4 不实现 C++11 范围循环.它还支持哪些其他范围循环语法
- for 带有容器的循环语法 - 是创建的副本
- C++中循环语法糖的简写(11)
- 不理解while循环语法
- 我收到错误 C2059:语法错误:'}'使用 Visual Studio 2013 进行边做循环练习
- VC++ 不再使用基于范围的语法对简单 FOR 循环进行矢量化
- 循环语法C++
- c++ 11 for循环语法不能正常工作
- 这种替代的"for"循环语法有什么依据吗?
- 从ofstream的文件名括号内输入代码值(如i从循环中输入)的c++语法
- 如何使用基于范围的循环语法在STL容器中的连续对上循环
- 循环短语法C++
- STL 容器基于范围的循环中的迭代器语法有什么区别
- 为什么 javascript 中不使用字符串循环的C++语法?