[英]Could anyone help me with what is wrong in the below piece of c++ code? The program doesn't give any output
The below code has been written aiming to generate all the armstrong* numbers below 1000.下面的代码旨在生成所有低于 1000 的 armstrong* 数字。
*armstrong numbers:An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. *阿姆斯特朗数:三位数的阿姆斯特朗数是一个整数,其数字的立方和等于该数本身。 For example, 371 is an Armstrong number since 3^3 + 7^3 + 1^3 = 371.例如,371 是一个阿姆斯特朗数,因为 3^3 + 7^3 + 1^3 = 371。
#include<iostream>
using namespace std;
int main()
{
int n,sum=0,digit,a,b;
for(n;n<1000;n++)
{
a=n;
b=n;
for(b;b>=0;b/10)
{
digit=b%10;
sum+=(digit*digit*digit);
}
(sum==a)?cout<<a:cout<<" ";
}
return 0;
}
n
is initially an undefined value. n
最初是一个未定义的值。 You'll need to set it to 0 before the for loop.您需要在 for 循环之前将其设置为 0。
Also, b
isn't being changed.此外, b
没有被改变。 Did you mean b /= 10
rather than b / 10
?你的意思是b /= 10
而不是b / 10
?
I'd suggest to structure the code to make it easier to read, eg by introducing a function bool isArmstrong(int number)
;我建议构造代码以使其更易于阅读,例如通过引入一个函数bool isArmstrong(int number)
; distinguish logic from using the logic;区分逻辑和使用逻辑; never let variables be uninitialised;永远不要让变量未初始化; introduce variables right there where they are used;在使用变量的地方引入变量; give variables a meaning by using names other than a
, b
;通过使用a
、 b
以外a
名称赋予变量意义;
Then things like not initialized variables or infinite loops become much more apparent:然后诸如未初始化变量或无限循环之类的事情变得更加明显:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
bool isArmstrong(int number) {
int cubeSum = 0;
for (int remainingPortion = number; remainingPortion > 0; remainingPortion/=10) {
int digit = remainingPortion % 10;
cubeSum += digit*digit*digit;
}
return (cubeSum == number);
}
int main() {
for (int number = 0; number < 1000; number++)
{
if (isArmstrong(number))
printf("%d is an armstrong number\n", number);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.