c++ - 如何输入不同的数字作为数组的不同元素?
问题描述
该程序基本上将 4568 之类的数字反转为 8654。它没有正确输入。我知道其他方法可以做到这一点,但你能建议我如何使这个程序工作。
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int num[25];
int a, b, c, d;
cout<<"Enter the no. which you want to reverse:\n";
cin>>num;
a = (int)sizeof(num)/4;
cout<<"The swapped no. is:\n";
for (b = a-1; b <= 0; b--)
{
cout<<num[b];
}
return 0;
}
解决方案
您的代码有一些错误。
a = (int)sizeof(c) / 4;
会将 的值初始化a
为 1(在sizeof(int)
等于 4 的平台中)。- for 循环无限迭代。这是因为
b
被初始化为零(如上所述和 1 - 1 = 0)并且停止条件设置为b <= 0
并且由于您b--
在每次迭代中都这样做,因此停止条件将始终为真。 cout << num[b];
语句不会反转存储在c
变量中的输入整数。您只是打印出数组中的一堆元素(可能为 0,也可能不是 0)。
一种可能的解决方案是使用std::string
.
#include<iostream>
#include <string>
//using namespace std; // Try not to use this. (see additional)
int main()
{
int c;
std::cout << "Enter the no. which you want to reverse:\n";
std::cin >> c;
std::string integerString = std::to_string(c); // Convert the integer to a string.
std::string reversed(integerString.rbegin(), integerString.rend()); // Use std::string s reverse iterators to initialize the reversed string.
std::cout << "The swapped no. is:\n" << reversed;
return 0;
}
编辑:至于您的评论,是的,我们可以使用一些简单的数学来完成它。
#include <iostream>
int main()
{
int c = 0;
std::cin >> c;
int biggestPower = 1;
for (; biggestPower < std::numeric_limits<int>::max(); biggestPower *= 10)
if (c < biggestPower) break;
int index = 0;
int sum = 0;
int list[25] = {};
for (; biggestPower > 0 && index < 25; biggestPower /= 10)
{
list[index] = (((c / biggestPower) * biggestPower) - sum) / biggestPower;
sum += ((c / biggestPower) * biggestPower) - sum;
index++;
}
for (index--; index > 0; index--)
std::cout << list[index];
}
例如,让我们使用 125 作为输入。
我们首先寻找可以适合输入值的 10 的最大幂(基本上是 10 的最大幂 < 输入值)。
然后我们可以使用它来获得三个值,{ 1, 12, 125 } 使用方程input value / powerOf10
。但是正如你所看到的,我们有像 12 和 125 这样的值,这是有问题的。
为了消除这一点,我们将第一个值(本例中为 1)乘以其位置值(即 100),得到新列表 { 100, 120, 125 }。现在我们只需要从下一个值(除了第一个)中减去前一个值,然后将它除以它的位置值,这给了我们各个数字 { 1, 2, 5 }。
我们可以使用它来反向返回它。
推荐阅读
- javascript - 在javascript中组合正则表达式
- azure - 具有持久功能的巨大 2 类队列操作计数
- c++ - 高斯模糊永远无法正常工作
- r - R中文件名列表中的矢量模式匹配和矢量替换
- sql - 两个模式之间的 Redshift 提取字符串 (regexp_substr)
- javascript - 修改父prototype.init()函数
- teamcity - 通过 TeamCity/Octopus 部署 ASP.NET 应用程序时,Application Insights 停止工作
- javascript - 使用 MomentJS 将 ISO 8601 转换为不同的 ISO 8601 格式
- substring - PowerBI DAX:在不重复 ID 的情况下计算变量的几个因素
- c# - 在表单关闭时等待任务完成