如何在这里循环运行?

How to run while loop here?

本文关键字:运行 循环 在这里      更新时间:2023-10-16

好的,这是我的代码,除了while循环之外,一切都工作正常。 该程序的目的是输入一个数字"40235",然后将其除以 10,取其余数 (5(,从主数中减去它,然后除以 10,得到它的完全商,即 4023。我确实设法运行了代码,但是循环没有迭代。(是的,我知道我必须取余数的总和,但首先我需要弄清楚如何迭代 while 循环(。 此循环必须迭代,直到 40235 变为零。

#include <iostream>
using namespace std;
int main()
{
cout<<"Program to yield exact quotient and sum of remainders: "<<endl;
int num, remainder_1, a, subtract;
cout<<"Enter a number: "<<endl
cin>>num;

while(num!=0)
{
remainder_1 =num%10;
num=num-remainder_1;
a =num/10;
cout<<a<<endl;
}
return 0;
}

代码中有多个问题:

  1. 你的循环条件相反,应该是while( num != 0 )
  2. 您无需从 num 中减去提醒,整数除法将处理
  3. 您不会将num/10分配回num因此,如果您的条件正确,您的循环将永远不会结束。

它应该是这样的:

while( num!=0 )
{
remainder_1 = num%10;
// do something with reminder
num /= 10; // short form of num = num / 10
}

试试

//...
while(num != 0)
{
//...

好吧,想通了。非常感谢大家!


#include <iostream>
using namespace std;
int main()
{
cout<<"Program to yield exact quotient and sum of remainders: "<<endl;
int num, remainder_1, a, subtract;
cout<<"Enter a number: "<<endl;
cin>>num;
int sum;
while(num!=0)
{
remainder_1 =num%10;
num/=10;
cout<<num<<endl;
sum+=remainder_1;
}
cout<<"The Sum is: t"<<sum<<endl;
return 0;
}