【问题标题】:is there a way to use Arrays in this C problem?有没有办法在这个 C 问题中使用数组?
【发布时间】:2021-10-26 07:39:08
【问题描述】:

我正在做这个问题:

“我们有一个巨大的十进制数N。编写一个程序来确定以下内容:

The number of digits in N.
Is N an even number?
The number of zeros in it.
Is N a multiple of 11? Note that we can determine if N is a multiple of 11 by checking the difference between the sum of the odd positioned digits and the sum of the even positioned digits. For example, 82375 is not a multiple of 11 because the sum of the even positioned digits is 2 + 7 = 9, and the sum of the odd positioned digits is 8 + 3 + 5 = 16, and the difference between 9 and 16 is 7, which is not a multiple of 11.

我们将为您提供每行的第一位数字。例如,如果你依次得到数字“1”、“2”、“3”、“4”、“0”,则数字为 12340。数字不会以 0 开头。 输入格式

输入有几行。每行都有一个数字。 EOF 表示输入结束。 输出格式

逐行输出上面的四个答案。如果数字是偶数,则输出 1;否则为 0。如果数字是 11 的倍数,则输出 1;否则输出 0。 子任务

10 points: you can store the decimal number in an integer without overflow
10 points: the number of digits is no more than 32768, so you can store digits in an array
80 points: you will get MLE if you use array"

我的代码是:

 #include <stdio.h>
#include <stdbool.h>

int digit(long n);
int is_even(int n);
int count_zeros(long n);
int is_multiple(long n);

int main() {

    int digits = 0;
    long x;

    scanf("%ld", &x);
    digit(x);
    int even = is_even(x);
    printf("%d\n", even);
    printf("%ld\n",count_zeros(x));
    printf("%ld\n", is_multiple(x));
}

int digit(long n)
{
    int digits = 0;
    while (n > 0) {
        n /= 10;
        digits++;
    }
    printf("%ld\n", digits);
}

int is_even(int n)
{
    if (n % 2 == 0)
        return true;
    else 
        return false;

}
int count_zeros(long n)
{
    int count = 0;
    while (n > 0) {
        n /= 10;
        if (n %10 == 0)
            count++;
    }

    return count;
}

int is_multiple(long n)
{
   if (n % 11 == 0) {
       return true;
   }
    else
        return false;
}
    

基本上我不知道如何满足问题的要求,所以我做了一个更简单的问题版本。关于如何做到这一点的任何线索?

如果您对此发表评论,请客气,我是初学者,过去人们很粗鲁,如果您没有什么要说的,请不要吝啬/不要评论。

【问题讨论】:

  • 您需要做的是将问题分解成更小的部分,然后当您遇到一个非常具体的问题时,请在 Stack Overflow 上提问。你会有更多的机会得到帮助。从读取输入开始并将其放入数组> 从输入读取直到遇到 EOF。然后才使用您提供的输入数据开始计算 - 您在正确的轨道上,但在处理数组时可能需要进行一些重构。
  • 总有一种方法可以使用数组来解决任何问题。更有趣的问题是是否可以避免使用数组或任何其他占用大量内存的数据结构。

标签: arrays c digits


【解决方案1】:

嗯,您当前版本的第一个问题是它只能读取一个整数。但是问题表明每个数字都在单独的行上。第一种方法可能只是用循环替换该 scanf 并保持乘以 10 并累积直到文件结束。然后程序的其余部分就可以正常工作了。

更高级的方法是使用数组来存储数字。一个整数可以容纳的位数非常有限,而使用数组时,您只受到可用内存大小的限制。

因此,在读取循环中,您可以将数字存储在一个数组中,而不是将数字存储在一个整数中(它可以是固定大小,因为给出了上限)。但是对于程序的其余部分,您应该将计算更改为使用数组中的数字而不是常规整数算术。

【讨论】:

  • 一种更高级的方法是不使用数组来存储数字。如果我正确理解子任务,它可以为你赢得 80 分。
猜你喜欢
  • 2022-09-27
  • 1970-01-01
  • 2020-02-09
  • 2015-08-13
  • 2011-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-24
相关资源
最近更新 更多