为什么我没有从字符串中获取数字 [英] Why I am not getting the number from string

查看:71
本文介绍了为什么我没有从字符串中获取数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个数字作为字符串输入并将其转换为数字但显示一点错误无法理解该怎么做..假设输入是123456789

和我的代码请将输出显示为123456785最后一位数字变化..请帮助..



我尝试过:



i am trying to take a number as string input and convert it to the number but its showing a little error cann't understand what to do..suppose the input was 123456789
and my code showing output as 123456785 change in the last digit..help please..

What I have tried:

#include <iostream>
#include <cmath>
using namespace std;

int main()
{

    string s;
    while(cin>>s)
    {
        long long number=0;
        int len=s.size();
        for(int i=len-1,j=0;i>=0;i--)
        {
            int digit=s[i]-'0';
            number+=digit*pow(10,j);
        j++;
        }
        cout<<number<<endl;
      
    }

    //cout << "Hello world!" << endl;
    return 0;
}

推荐答案

你的代码在我的Lubuntu盒子上工作正常(g ++ 4.7.3)。

您也可以这样写它

You code works fine on my Lubuntu box (g++ 4.7.3).
You may also write it this way
 #include <iostream>
 #include <cmath>
using namespace std;

int main()
{
  string s;
  while ( cin >> s)
  {
    long long number = 0;
    for (const auto & c : s)
    {
      number *= 10;
      number += c -'0';
    }
    cout << number << endl;
  }
}


我刚刚在Ubuntu上用GCC(g ++)测试它,它显示的是正确的结果。



您错误的输出表明可能存在使用 pow()函数引入的舍入错误。根据您的编译器和 math.h / cmath 头文件,它可能使用浮点或模板。





使用VS时, math.h 中的内联函数使用 _Pow_int 模板头文件:

I just tested it with GCC (g++) on Ubuntu and it is showing the correct result.

Your wrong output indicates that there is probably a rounding error which may be introduced by using the pow() function. Depending on your compiler and the math.h / cmath header file it may use floating point or a template.


When using VS there is a _Pow_int template used with inline functions in the math.h header file:
inline double __cdecl pow(int _X, int _Y)
        {return (_Pow_int(_X, _Y)); }



因此权力从整数计算,返回的结果转换为 double 。然后将此结果转换为 long long 。这两次转换可能会导致舍入错误。

[/编辑]



但你可以避免使用 pow( )通过重写你的函数:


So the power is caluclated from integers and the returned result is converted to double. This result is then converted to long long. These two conversions may lead to rounding errors.
[/EDIT]

But you can avoid using pow() by rewriting your function:

long long number=0;
int len = s.size();
for (int i = 0; i < len; i++)
{
    int digit=s[i] - '0';
    number *= 10;
    number += digit;
}
cout<<number<<endl;


这篇关于为什么我没有从字符串中获取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆