如何在第 "." 点之后将数字放入数组中

How to get numbers into array after point "."

本文关键字:数字 数组 之后      更新时间:2023-10-16

我如何将数字放入数组中,如11*11 = 121,我如何将121作为1,2,1放入数组中,以便它应该像int arr[] = [1,2,1];一样,对我来说,一个逻辑是将其除以10,我正在尝试的代码是

    long mul , cube;
    mul = num*num;
    cube = num*num*num;
    float unt = mul/10.0;

但是如何保存数字后周期.到数组,就像如果我有数字2.3,所以我想保存3到数组

我认为你想把单个数字放入数组中。

您可以按照算法(让n为您想要分割的数字)将数字按相反顺序放入数组中:

while (n > 0):
   push (n mod 10) into the array --- this is one digit from 0..9
   divide n by 10, ignoring the decimal part (ignoring remainder, that is)

例如,当n=97时,你得到:

(n mod 10) = 7, push that into array
divide 97 by 10 to get 9 (ignoring .7)
(n mod 10) = 9, push that into array
divide 9 by 10 to get 0
end algorithm

现在数组中有[7,9],然后将数组反向以获得从左到右的顺序

继续从OP请求代码示例,以及我对问题的理解。这从另一个答案(Antti Huima)实现了算法;

#include <iostream>
#include <vector>
#include <algorithm>
std::vector<int> convert(int number)
{
    std::vector<int> result;
    if (number == 0) {
        result.push_back(0);
    }
    while (number) {
        int temp = number % 10;
        number /= 10;
        result.push_back(temp);
        //result.insert(result.begin(), temp); // alternative... inserts in "forward" order
    }
    // push_back inserts the elements in reverse order, so we reverse them again
    std::reverse(result.begin(), result.end());
    return result;
}
int main()
{
    int i = 123;
    auto result = convert(i);
    std::cout << i << std::endl;
    for (auto& j : result) {
        std::cout << j << ',';
    }
    std::cout << std::endl;
}

它的实现假定了某些基础(可以修改或模板化);

  • int基类型和int作为数组成员
  • 可变数组大小(在vector中)
  • convert是一个非常随意的名字
  • main只是一个使用的演示(所以我在c++ 11语言的使用上更自由一点)。

生活代码