【问题标题】:Is this a correct way of doing this in C?这是在 C 中执行此操作的正确方法吗?
【发布时间】:2022-01-06 16:12:27
【问题描述】:

我应该更改书面代码中的某些内容吗?编译器说一切正常——没有错误或警告。

  • 您正在建造一个新家,并且您已经准确计算了地基所需的水泥量。
  • 理想情况下,您想购买确切数量的水泥,但商店只出售 120 磅袋装的水泥。
  • 这些包每个售价 45 美元。

请编写一个 C 程序,计算您为建造地基而必须购买的水泥成本。

  • 您的程序应首先读取一个十进制数字,该数字表示新家地基所需的水泥量(以磅为单位)。
  • 然后,您的程序应显示您必须购买的水泥袋的总成本,以获得足够的水泥来建造地基。
  • 为了使您的程序更简单,您需要保证所需的水泥量永远不会是 120 的倍数。

到目前为止我的代码:

#include <stdio.h>
#include <math.h>
int main(void) {
    int price=45, totalPrice, OneBag=120;
    float needed;
    do
    {
        printf("Enter the amount of cement you need for your foundation that is not dividable by 120: ");
        scanf("%f", &needed);
    } while (fmodf(needed, OneBag)==0);
    
    totalPrice = ((int)needed/OneBag+1)*(price);
    printf("Total cost of cement you will need for your foundation is %d", totalPrice);
    

    return 0;
}

【问题讨论】:

  • 欢迎来到 SO。 您可以保证所需的水泥量永远不会是 120 的倍数。 这并不意味着 必须确保这一点。此外,您应该始终检查 scanf 的返回值。
  • 你测试了吗? 119、121、239、241、240.01、239.99 作为您需要的水泥量,它是否给出了正确答案?
  • 关于“编译器说一切都是正确的”:没有编译器会这么说。编译器最多会告诉你的是它没有发现任何问题。这并不意味着它没有发现问题。
  • 是什么让你觉得这有些不对劲?
  • @S3gfault 我会给你几个困扰我的例子 1. 在 fmodf(needed, OneBag) 中我可以使用如上所述的整数,但是当我尝试这样做时:需要%120= = 0 我得到这个“二进制 % 的无效操作数(具有 'float' 和 'int')” fmodf 会自动将整数更改为浮点数吗? 2. 如果我先这样做:totalPrice = ((int)needed/OneBag+1) 然后 printf("%d", totalPrice*price);这是正确的。但是这个:totalPrice = (needed/OneBag+1)*(price); printf("%d", totalPrice);不是。

标签: c integer fmod fmodf


【解决方案1】:

说实话,我没有看到您的代码中有任何真正的错误,但在我看来,还有改进的余地:

每袋的价格和袋子的大小都是常量,您实际上可以在代码中明确说明,这样更具可读性,并且可以让编译器更好地优化您的代码。

您实际上也不必检查输入是否是 120 的倍数,因为它不是。

还有一个叫做ceil 的函数(或者ceilf,如果使用浮点数),它实际上接受任何数字并向上增加到最接近的整数。这对这个作业非常有用。

最后一件事仅仅因为编译器说没问题,并不意味着它实际上是。

代码:

#include <stdio.h>
#include <math.h>

const float price_per_bag = 45;
const float bag_size = 120;

int main(void) {
    float needed;
    printf("Enter the amount of cement needed:\n");
    scanf("%f", &needed);

    float price = ceilf(needed / bag_size) * price_per_bag;
    printf("total price: %i\n", (int)price);
}

【讨论】:

    【解决方案2】:
    #include <stdio.h>
    
    int main(void){
          
       float totalC;
       int count=0, totalPrice, i ;
          
       scanf("%f", &totalC);
    
       for (i=0; i<totalC; i+=120)
            {
               count = count+1;   
             }
         
    
             totalPrice = count *45;
             printf("%d", totalPrice);
             return 0;
    
          }
    

    【讨论】:

    • 你的答案只是一段代码,没有上下文。为了帮助其他程序员改进,最好添加一些关于您的代码 sn-p 应该解决什么以及如何解决的说明。
    猜你喜欢
    • 2021-08-23
    • 2014-01-29
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 2012-09-19
    • 1970-01-01
    相关资源
    最近更新 更多