我在c ++中有一个循环错误
I have a cycle error in c ++
当用户添加了他想重复循环的次数,但他一直重复循环没有结束时产生错误
这是代码
#include <iostream>
using namespace std;
int main()
{
char resp, copcion, varied, tprod;
int cfab, ncod, num;
cout << "How many products do you want to register ?, enter the respective number";
cin >> num;
while (num > 0)
{
cout << "Enter the product type If you are a Child (n) or Adult (a)";
cin >> tprod;
if ((tprod != 'n') && (tprod != 'N') && (tprod != 'a') && (tprod != 'A'))
{
cout << "ERROR: The product type is only Children (n) or Adults (a)" << endl;
}
cout << "Enter your Variety for Salted (s) and Sweets (d)";
cin >> varied;
if ((varied != 'd') && (varied != 'D') && (varied != 's') && (varied != 'S'))
{
cout << "ERROR: The variety of products are only Sweets (d) or Salted (s)" << endl;
}
//Code range
//Salted 1 to 10
//Sweets 11 to 20
cout << "Enter the product code you wish to assign";
cin >> ncod;
if (ncod > 20)
{
cout << "ERROR: There is a range of numbers, you exceeded that amount" << endl;
}
cout << "Enter the respective amount";
cin >> cfab;
if (cfab = 0)
{
cout << "ERROR: Amount entered is not valid";
}
}
return 0;
}
先谢谢解惑
代码将一个数字读入 num
变量并执行 while(num>0)
- 但它永远不会改变 num
所以它总是大于 0 并永远循环。
也许将 while(num>0) {
更改为 while(num-- > 0) {
以每次递减 num
并且循环将 运行 num
次而不是无限次。
当用户添加了他想重复循环的次数,但他一直重复循环没有结束时产生错误
这是代码
#include <iostream>
using namespace std;
int main()
{
char resp, copcion, varied, tprod;
int cfab, ncod, num;
cout << "How many products do you want to register ?, enter the respective number";
cin >> num;
while (num > 0)
{
cout << "Enter the product type If you are a Child (n) or Adult (a)";
cin >> tprod;
if ((tprod != 'n') && (tprod != 'N') && (tprod != 'a') && (tprod != 'A'))
{
cout << "ERROR: The product type is only Children (n) or Adults (a)" << endl;
}
cout << "Enter your Variety for Salted (s) and Sweets (d)";
cin >> varied;
if ((varied != 'd') && (varied != 'D') && (varied != 's') && (varied != 'S'))
{
cout << "ERROR: The variety of products are only Sweets (d) or Salted (s)" << endl;
}
//Code range
//Salted 1 to 10
//Sweets 11 to 20
cout << "Enter the product code you wish to assign";
cin >> ncod;
if (ncod > 20)
{
cout << "ERROR: There is a range of numbers, you exceeded that amount" << endl;
}
cout << "Enter the respective amount";
cin >> cfab;
if (cfab = 0)
{
cout << "ERROR: Amount entered is not valid";
}
}
return 0;
}
先谢谢解惑
代码将一个数字读入 num
变量并执行 while(num>0)
- 但它永远不会改变 num
所以它总是大于 0 并永远循环。
也许将 while(num>0) {
更改为 while(num-- > 0) {
以每次递减 num
并且循环将 运行 num
次而不是无限次。