简体   繁体   English

c++ 中 integer 的第一个和最后一个数字的总和

[英]sum of first and last digit of integer in c++

#include<iostream>
#include<math.h>
int main()
{
  int n,first,last,digits;
  cin>>n;
  last=n%10;
  digits=log10(n);
  first=n/pow(10,digits);
  cout<<first+last;`
}

The above code shows 2 as output for the input 0101 but it should show 1.since 0+1=1.can anyone suggest code in c++?上面的代码显示 2 为 output 用于输入 0101 但它应该显示 1.since 0+1=1.任何人都可以在 c++ 中建议代码吗?

Your input is 0101 into n.您的输入是 0101 到 n。 n is an int . n 是一个int So the preceding useless 0 in 0101 is shaved off and you get the correct answer for 101 (1 + 1 = 2).所以前面 0101 中无用的 0 被剃掉,你得到 101 的正确答案(1 + 1 = 2)。 You'll need to use a string if you want to get 1 for 0101.如果要为 0101 获取 1,则需要使用字符串。

It's a math, you can expression to get the first (most significant digit) of an integer number:这是一个数学运算,您可以通过表达式获得 integer 数字的第一个(最高有效位):

first = n / static_cast<int>(pow(10, static_cast<int>(log10(n))));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM