【问题标题】:Why is my program printing 0 instead of the intended value? (C) [duplicate]为什么我的程序打印的是 0 而不是预期的值? (C) [重复]
【发布时间】:2020-09-01 20:20:20
【问题描述】:

我正在尝试为我的班级制作一个计算器程序(如您所知,尚未完全完成),但我遇到了乘法和除法部分的问题。它们都打印出 0 而不是它们的预期值,但加法和减法工作正常。有什么帮助吗?

int choice = 8;
double numberone;
double numbertwo;
    
while(choice > 7 || choice < 1){
    printf("(1) Addition \n(2) Subtraction \n(3) Multiplication \n(4) Division \n(5) Modulus (integers only) \n(6) Test if prime (integers only) \n(7) Exit \nPlease choose an operation: \n");
    scanf(" %i", &choice);
    
    if (choice != 5 || choice!= 6){
        printf("Enter the first number: ");
        scanf(" %d", &numberone);
        
        printf("Enter the second number: ");
        scanf(" %d", &numbertwo);
        
        if (choice == 1){
            double sum = numberone + numbertwo;
            printf("Sum: %d", sum);
        }
        else if (choice == 2){
            double dif = numberone - numbertwo;
            printf("Difference: %d", dif);
        }
        else if (choice == 3){
            double pro = numberone * numbertwo;
            printf("Product: %d", pro);
        }
        else if (choice == 4){
            double quo = numberone / numbertwo;
            printf("Quotient: %d", quo);
        }
    }
}
}

【问题讨论】:

  • ans 显示实际和预期的输入和输出。
  • (choice != 5 || choice!= 6) 将永远为真。你想在这里做什么?
  • 阅读double需要使用%lf格式,而不是%d
  • 所有scanf()a的返回值(不是扫描的值)是什么?现在改掉不理他们的习惯。

标签: c


【解决方案1】:

您在printf 中使用%d,它将您的结果转换为整数。请改用%lf

// ...
        else if (choice == 3){
            double pro = numberone * numbertwo;
            printf("Product: %lf", pro);
        }
        else if (choice == 4){
            double quo = numberone / numbertwo;
            printf("Quotient: %lf", quo);
// ...

编辑: 这同样适用于您的 scanf。使用%lf 而不是%i

// ...
       printf("Enter the first number: ");
       scanf(" %lf", &numberone);
        
       printf("Enter the second number: ");
       scanf(" %lf", &numbertwo);
// ...

【讨论】:

  • 他还在scanf中使用%d
  • @Barmar 哦,你是对的。谢谢
猜你喜欢
  • 2019-12-07
  • 1970-01-01
  • 2017-08-29
  • 2016-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多