首页 > 解决方案 > 如何输入不同的数字作为数组的不同元素?

问题描述

该程序基本上将 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;

}

标签: c++arraysreversecin

解决方案


您的代码有一些错误。

  1. a = (int)sizeof(c) / 4;会将 的值初始化a为 1(在sizeof(int)等于 4 的平台中)。
  2. for 循环无限迭代。这是因为b被初始化为零(如上所述和 1 - 1 = 0)并且停止条件设置为b <= 0并且由于您b--在每次迭代中都这样做,因此停止条件将始终为真。
  3. 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 }。
我们可以使用它来反向返回它。


推荐阅读