[英]Strange output using array in c++
I am working on one of the programs using arrays. 我正在使用数组的程序之一。 What I want is to..add the elements of the char array and give the output.
我想要的是..添加char数组的元素并给出输出。 Here's the code:
这是代码:
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char number[8];
int in , i = 0 , square = 0;
cin>>number;
while(1){
if(i != strlen(number)){
square = (number[i]) + square;
cout<<square<<"\n";
}
else{
break;
}
i++;
}
cout<<square - 48*(strlen(number));
return 0;
}
the strange thing is that the output is 48 x (the number of digits of input) more than the original input, that is why I have subtracted that part from the output. 奇怪的是输出比原始输入多48倍(输入的位数),这就是为什么我从输出中减去了那部分的原因。 Why this happens?
为什么会这样?
number[i]
is a character, but you are treating it as if it was an integer. number[i]
是一个字符,但是您将其视为整数。 '0'
(a character) does not equal 0
(an integer), '1'
does not equal 1
etc. The simple way to convert a decimal digit character to an integer is to subtract '0'
from it. '0'
(字符)不等于0
(整数), '1'
不等于1
等等。将十进制数字字符转换为整数的简单方法是从中减去'0'
。 Like this 像这样
square = (number[i] - '0') + square;
'0' - '0'
does equal 0
, '1' - '0'
does equal 1
, etc. '0' - '0'
等于0
, '1' - '0'
等于1
,依此类推。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.