如何在第 "." 点之后将数字放入数组中
How to get numbers into array after point "."
我如何将数字放入数组中,如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语言的使用上更自由一点)。
生活代码
相关文章:
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和
- 数组/c++中的大量数字
- 遍历并行数组以确定C++中的最大数字
- 整数区间(或 int 数组)中每个数字的出现次数
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 获取 2D 数组 c++ 中的所有数字对
- 为什么使用数组元素查找最大数字的程序不起作用?
- 如何从向量或数组中选择最常见的数字?(前五名)C++
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 以十为基数的数字到布尔数组,该数组要求二进制/基数为 2 的数字
- C++ 检查结果数组中有多少次数字
- 如何在不使用 C++ 中的数组或函数的情况下查找 N 位数字的所有排列
- 如何在C++中有效地将数字值重新分配给字符数组
- 查找数组中的最小数字
- 查找数组中重复(重复)数字的索引
- 我必须找到给定数组中所有数字的周期,就像有很多解决方案,但数组的大小是 10^5
- 类、数字/数组或对象中的对象