【问题标题】:Correct my thinking in this C exercise [closed]在这个 C 练习中纠正我的想法 [关闭]
【发布时间】:2013-03-06 01:58:24
【问题描述】:

该练习要求找出从 1 到 500 的数字中的哪一个,即数字特定数字的总和,乘以三次方等于该特定数字。

例如 1^3=1 和 371 使 3^3+7^3+1^3 = 371

我是如何解决这个问题的:

我在想如果我可以有一个包含 500 个插槽的字符串数组,每个插槽包含一个字符串转换后的数字,那么我可以对每个插槽的字符串进行数学运算。如果他们符合我将应用的标准,那么将打印该插槽。

我尝试了 sprintf 函数但没有成功。在一个循环中,它只是初始化字符串(或者它是数组?3 小时后我很困惑)[0] 插槽,而所有其他插槽保持不变。

我不想让你解决这个练习,而不是用我的逻辑来指导我。如果你愿意,请让我添加我所做的代码。

【问题讨论】:

  • 面对您的想法的最佳方式是实施它并了解它是如何运作的。然后当你以后遇到一些具体的问题时,你可能会回到这里再次询问。
  • 首先编写一个函数,它接受一个数字作为输入参数,并通过分别返回 1 或 0 来告诉您该数字是否满足指定条件。
  • 很高兴你写了一些关于如何解决它的想法,但是这里的人们想看看你实际尝试了什么。
  • 请不要使用字符串来解决数学问题。您将很快耗尽内存和 CPU 时间。使用模算术和整数除法从数字中获取特定数字。
  • 0、1、153、370、371 和 407 只是 1 到 500 之间的数字。直接打印出来 ;)

标签: c algorithm


【解决方案1】:

始终从明确定义您的算法开始,这样您就知道自己在做什么。把它分成简单的步骤。像这样的:

For each integer i in the interval 1 to 500:
  Check if the condition holds for this i
  If it holds:
    Print i
  else:
    Do nothing

现在您需要定义“检查此 i 的条件是否成立”。我会使用一些模数和除法运算来提取数字,但我把细节留给你。

请注意,我没有谈论 C 或任何其他编程语言。只有当你知道你的算法时,你才应该开始考虑实现。

(实际上可能有一种与上面给出的算法略有不同的算法,其中每个嵌套的数字都有一个循环。该解决方案可能对您来说是可以接受的,但它不会那么通用)

【讨论】:

    【解决方案2】:
    for(i=1;i<=500;i++)
    {
       //loop for checking each number i
       int sum=0; // to store the sum of cube of digits
       int n=i; //copy of i
       //The below while loops does the task. It extracts a digit from the number and adds its cube to the sum
       // last digit from the number can be seen by taking its remainder by 10 . For eg 35%10=5
       //once we have used this digit make the number shorter by dividing by 10. For eg 35/10 becomes 3 (because of integer divisions)
       while(n>0)
       {
           int rem=n%10; //extract the last digit
           sum+=cube(rem); //cube function raises a number to its cube
           n/=10;  //remove the digit we had extracted earlier from the number
        }
        if(sum==i) //we got the number we wanted
            printf("%d\n",i);
    
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-10
      • 1970-01-01
      • 2014-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      • 2011-03-17
      • 1970-01-01
      相关资源
      最近更新 更多