【问题标题】:Incorrect result checking for Fisher numbers [closed]Fisher数的结果检查不正确[关闭]
【发布时间】:2018-08-03 15:45:34
【问题描述】:

计划详情:Fisher 编号

Fisher 数是一个整数,其因数(包括其自身)的乘积等于该数的立方。例如,12 是 Fisher 数,因为 123 = 2 x 3 x 4 x 6 x 12。

示例:

Input: 12  
Output: true (12<sup>3</sup> = 2 x 3 x 4 x 6 x 12)

Input: 8  
Output: false (8<sup>3</sup> != 2 x 4 x 8)

目标:

  • 编写一个程序来检查用户输入的是否是 Fisher 数。
  • 打印给定范围内的所有 Fisher 数

这是我的代码:

#include <stdio.h>
#include <conio.h>
int ch, product = 1, cube, num, i, j, min, max;

// Check Function

void check() {
    int i;
    printf("Enter the Number to check whether It is Fisher or Not\n");
    scanf("%d", &num);
    cube = num * num * num;
    for(i = 2; i <= num; i++) {
        if(num % i == 0) {
            product = product * i;
        }
    }
    if(cube == product) {
        printf("It is a Fisher Number!\n");
    }
    else {
        printf("It is not a Fisher Number\n");
    }
}

// RANGE FUNCTION

void range() {
    printf("Enter the Minimum and Maximum value of Range\n");
    scanf("%d%d", &min, &max);
    for(i = min; i <= max; i++) {
        cube = i * i * i;
        for(j = 1; j <= i; j++) {
            if(i % j == 0) {
                product = product * i;
            }
        }
        if(cube == product) {
            printf("%d\n", i);
        }
    }
}

void main() {
    clrscr();
    printf("Enter Your Choice \n");
    printf("1 - Check Fisher Number \n");
    printf("2 - Display Fisher Numbers in a Range \n");
    scanf("%d", &ch);
    switch(ch) {
        case 1: check();
                break;
        case 2: range();
                break;
        default: printf("Enter Valid Choice \n");
    }
    getch();
}

Output picture 和文字:

Enter Your Choice 
1 - Check Fisher Number 
2 - Display Fisher Numbers in a Range 
2
Enter the Minimum and Maximum value of Range
1 40
1

我没有得到正确的范围输出。例如,如果范围设置为 1 到 15,则只显示1,这是错误的!

【问题讨论】:

  • 什么错误?确保包含所有相关信息。
  • 我没有得到正确的范围输出。例如,如果范围设置为 1 到 15,则只显示 1,这是错误的!
  • 请以适当的格式将您的“例如”添加到问题中。此外,“这是错误的”是不够的 - 还要显示 预期的结果。
  • 你应该阅读how to debug small programs
  • 另外,作为未来的一般指导方针:当你有两个函数都需要执行相同的重要任务时(例如,检查整数是否是 Fisher 数),编写第三个函数调用IsFisherNumber,他们都可以调用,而不是执行算法两次。您的代码将更易于理解和维护。

标签: c function loops


【解决方案1】:

你应该在这里乘以j

if(i%j == 0) {
    product = product * i;
}

如果您使用比ij 更有意义的变量名,会更明显。

你还需要在内部循环之前重置product变量(为什么它还是一个全局变量?你不知道它们是邪恶的吗?)

cube = i * i * i;
product = 1;
for(j=1;j<=i;j++) { ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2021-07-23
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    相关资源
    最近更新 更多