因此,需要做的是:输入一个实数并在小数点后打印其前4位数字的总和。例如:我输入5.1010。我到了需要将0.1010乘以10000的地步,以便它可以成为整数,但是我得到的结果是1009而不是1010,然后一切都崩溃了。
如果有人可以向我解释为什么会发生,我将永远感激不已。

#include<iostream>
using namespace std;

int main()
{
  double n;
  cout<<"Enter a positive real number: ";
  do
  {
    cin>>n;
    if(n<=0) cout<<"The number must be positive, enter again: ";
  }while(n<=0);

    //storing the fractional part in a var
  int y=n;
  double fr=n-y;
  //turning the fractional part into an integer
  int fr_int=fr*10000;
  cout<<fr_int<<endl;

  //storing each of the digits in a var
  int a=fr_int/1000;
  int b=fr_int/100%10;
  int c=fr_int/10%10;
  int d=fr_int%10;

  cout<<"The sum of the first 4 digits is: " << a+b+c+d;
  return 0;
}

最佳答案

您可以按如下所示简单地更改代码,然后它应该可以工作了。

  n *= 10000;
  int Integer = n;

  int i = 4;
  int sum = 0;
  while(i--)
  {
    sum += (Integer%10);
    Integer /= 10;
  }
  std::cout << "The sum of the first 4 digits is: " << sum;

输出为:https://www.ideone.com/PevZgn

更新:广义的soln将使用std::string。但是,如果代码能够处理用户提交的非数字的异常,那就太好了。
#include <iostream>
#include <string>

int main()
{
  std::string Number;
  double tempNum = 0.0;

  std::cout << "Enter a positive real number: ";
  do
  {
    std::cin >> Number;
    tempNum = std::stof(Number);

    if(tempNum <= 0)
      std::cout << "The number must be positive, enter again: ";
  }while(tempNum <= 0);

  bool Okay = false;
  int sum = 0;
  int i = 4;

  for(const auto& it: Number)
  {
    if(Okay && i > 0)
    {
      sum += static_cast<int>(it - '0');
      --i;
    }
    if(it == '.') Okay = true;
  }
  std::cout << "The sum of the first 4 digits is: " << sum;

  return 0;
}

10-06 15:07