英文:
Why does it tell me its an Armstrong number when I enter strings?
问题
这是用于查找一个三位数的阿姆斯特朗数的代码。但是,当我输入字符串或任何其他特殊字符时,它会将其分类为阿姆斯特朗数,而实际上应该相反。
#include <stdio.h>
#include <stdlib.h>
int main() {
int a, original, rev, rem;
printf("输入数字:\n");
scanf("%d", &a);
original = a;
rev = 0;
while (a != 0) {
rem = a % 10;
rev = rev + (rem * rem * rem);
a /= 10;
}
if (rev == original) {
printf("这是一个阿姆斯特朗数\n");
} else {
printf("这不是一个阿姆斯特朗数\n");
}
}
英文:
This is the code for finding an Armstrong number of 3 digits. But when i enter strings or any other special character it categorizes it as an armstrong number while it should be other way around.
#include <stdio.h>
#include <stdlib.h>
int main() {
int a, original, rev, rem;
printf("Enter the number : \n");
scanf("%d", & a);
original = a;
rev = 0;
while (a != 0) {
rem = a % 10;
rev = rev + (rem * rem * rem);
a /= 10;
}
if (rev == original) {
printf("Its an Armstrong number\n");
} else {
printf("Its not an Armstrong number \n");
}
}
答案1
得分: 3
这是未定义行为,因为您使用了未初始化的变量 a
。
您应该检查不正确的输入:
if (scanf("%d", &a) != 1)
{
printf("无效的输入\n");
return 1;
}
英文:
It is Undefined Behaviour as you use not initialized variable a
.
You should have checked for the incorrect input:
if(scanf("%d", &a) != 1)
{
printf("Invalid input\n");
return 1;
}
答案2
得分: 3
你需要检查 scanf
的结果 - 它将返回成功转换和分配的项目数量。
if (scanf("%d", &a) != 1)
// 输入错误
else
// 检查 a 是否是阿姆斯特朗数
像 `nnnniii` 这样的输入不是有效的整数,所以读取失败,`a` *不会被更新*。
虽然 `auto` 变量的初始值是*不确定的*,但 `a` 可能具有初始值 `0`,所以你的测试会偶然通过。
英文:
You need to check the result of scanf
- it will return the number of items successfully converted and assigned.
if ( scanf( "%d", &a ) != 1 )
// bad input
else
// check if a is an armstrong #
An input like nnnniii
is not a valid integer, so the read fails and a
is not updated.
While the initial value of auto
variables is indeterminate, it's possible that a
has an initial value of 0
, so your test passes by accident.
答案3
得分: 1
#include <stdio.h>
#include <stdlib.h>
int main() {
int a, original, rev, rem;
printf("Enter the number : \n");
if(scanf("%d", &a) != 1)
{
printf("This is not a number\n");
return 1;
}
original = a;
rev = 0;
while (a != 0) {
rem = a % 10;
rev = rev + (rem * rem * rem);
a /= 10;
}
if (rev == original) {
printf("It's an Armstrong number\n");
} else {
printf("It's not an Armstrong number\n");
}
}
When you get a value, you need to check if it is a number or not.
英文:
#include <stdio.h>
#include <stdlib.h>
int main() {
int a, original, rev, rem;
printf("Enter the number : \n");
if(scanf("%d", &a) != 1)
{
printf("This is not number\n");
return 1;
}
original = a;
rev = 0;
while (a != 0) {
rem = a % 10;
rev = rev + (rem * rem * rem);
a /= 10;
}
if (rev == original) {
printf("Its an Armstrong number\n");
} else {
printf("Its not an Armstrong number \n");
}
}
When you get value, you need to check it is number or not.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论