C++循环查找"sum of digits of a given number"



我是初学者。我试图解决一些问题,却卡在了第一个问题上。while循环运行了但是我试着使用for循环,它从来没有运行过

#include <iostream>
using namespace std;
int main(){
int n=910;
int digits_sum=0;
for(int i=n;i=0;i/=10)
digits_sum+=(i%10);
cout<<digits_sum;
return 0;}

我在谷歌上找到了codescrackers:

int num, rem, sum;
cout<<"Enter the Number: ";
cin>>num;
for(sum=0; num>0; num=num/10)
{
rem = num%10;
sum = sum+rem;
}
cout<<"nSum of Digits = "<<sum;

代码运行了,它给了我其他的问题:

  1. 为什么初始值sum=0?
  2. 为什么condition number>0

似乎我仍然没有完全得到for循环语句,所以这是我理解的运行方式:

init value I = n = 910

跳出循环的条件:I = 0

减量:I = 910/10 = 91

你能告诉我我哪里做错了吗?

引用你的问题:

条件出环:i=0

你有两个误解:

  1. i = 0是赋值,您需要比较i == 0
  2. 看起来你把它解释为&;exit,如果这个条件是满足的,但实际上恰恰相反:只要这个条件为真,循环就会继续。

所以你唯一要做的就是改变

for(int i=n;i=0;i/=10)

for(int i = n; i != 0; i /= 10) // loop as long as i does not equal 0

相关内容

最新更新