阿姆斯特朗数字的代码不起作用
Code for Armstrong numbers not working
好吧,请放轻松。只是学习C++,首先在这里提问。我写了一个程序来列出所有低于1000的阿姆斯特朗数字。虽然我已经阅读了维基百科关于自恋数字的文章,但我只在寻找 3 位数的数字。这意味着我只关心数字立方体的总和。
它的工作原理是执行 1 到 1000 的 for 循环,使用用户定义的函数检查索引变量是否为 armstrong,如果是,则打印它。用户定义的函数只需使用 while 循环来隔离数字并将立方体的总和与原始数字匹配即可。如果为 true,则返回 1,否则返回 0。
问题是,我在输出中得到的绝对没有数字。只有 void main() 中的 cout 语句出现,其余的为空。试图尽可能多地调试。Complier是Turbo C++。法典-
#include<iostream.h>
#include<conio.h>
int chk_as(int);//check_armstrong
void main()
{
clrscr();
cout<<"All Armstrong numbers below 1000 are:n";
for(int i=1;i<=1000;i++)
{
if (chk_as(i)==1)
cout<<i<<endl;
}
getch();
}
int chk_as (int n)
{
int dgt;
int sum=0,det=0;//determinant
while (n!=0)
{
dgt=n%10;
n=n/10;
sum+=(dgt*dgt*dgt);
}
if (sum==n)
{det=1;}
else
{det=0;}
return det;
}
问题是您正在动态更改方法中 n 的值,但您需要其原始值来检查结果。
添加一个临时变量,例如 t。
int t = n;
while (t!=0)
{
dgt=t%10;
t=t/10;
sum+=(dgt*dgt*dgt);
}
if (sum==n)
// ... etc.
编辑:没关系...这是错误的
while (n!=0)
{
dgt=n%10;
n=n/10;
sum+=(dgt*dgt*dgt);
}
这将永远运行,因为n
永远不会达到 0。
问题是,在循环的末尾
while (n!=0)
{
dgt=n%10;
n=n/10;
sum+=(dgt*dgt*dgt);
}
n 为 0,因此条件if (sum==n)
永远不会为真。
尝试类似以下内容:
int chk_as (int n)
{
int copy = n;
int dgt;
int sum=0,det=0;//determinant
while (copy!=0)
{
dgt=copy%10;
copy=copy/10;
sum+=(dgt*dgt*dgt);
}
if (sum==n)
{det=1;}
else
{det=0;}
return det;
}
我在这里给出了查找三位数字的阿姆斯特朗数的程序。
阿姆斯特朗数的条件是,其数字的立方体之和必须等于数字本身。
例如,407 作为输入给出。4 * 4 * 4 + 0 * 0 * 0 + 7 * 7 * 7 = 407 是一个阿姆斯特朗数。
#include <stdio.h>
int main()
{
int i, a, b, c, d;
printf("List of Armstrong Numbers between (100 - 999):n");
for(i = 100; i <= 999; i++)
{
a = i / 100;
b = (i - a * 100) / 10;
c = (i - a * 100 - b * 10);
d = a*a*a + b*b*b + c*c*c;
if(i == d)
{
printf("%dn", i);
}
}
return 0;
}
介于 (100 - 999) 之间的阿姆斯壮数列表:153370371407
参考: http://www.softwareandfinance.com/Turbo_C/Find_Armstrong_Number.html
相关文章:
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 为什么这段代码不起作用,我该如何解决?
- 为什么这些完全相似的代码不起作用?
- 我不明白为什么我的代码不起作用并且需要更长的时间来运行
- 我正在尝试解决一个需要数组总和值但代码不起作用的问题,我想做这样的事情
- 代码在Visual Studio 2017中不起作用,但在VS代码中工作
- std::string == 运算符在代码中不起作用
- C++ 多态性在代码::块 17.12 中不起作用
- 为什么 pop_back() 在此代码中不起作用?
- 注释一行使代码工作,而没有它,代码不起作用
- C++ 程序在代码块 IDE 中不起作用
- 代码编译但不起作用!cmd窗口只是理想和理想,但什么也没发生
- 我的C++合并排序代码不起作用。我在这里错过了什么?
- 在 directx11 代码中更改全屏模式下的刷新率不起作用
- 为什么给定的代码不适用于所有测试用例?为什么当输入为 7786 时它不起作用?
- cpp / c ++中的grpc客户端代码,元数据x-api-key/x-goog-api-key不起作用,给了我语音A
- C ++函数重新定义(代码不起作用 - 逻辑错误)
- 试图找到一个数字的平方根,但代码不起作用。C++