且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

需要C程序练习的帮助

更新时间:2023-11-20 15:55:22

假设您的输入没有备注,即

Assuming your input is without remarks, i.e.
1.42
2.25
30.21
0 200
1 400
2 100



你可以阅读整行,测试是否包含两个整数(数量和数量)或只是一个浮点数(价格)。那是


You could read the whole line, the test if it contains two integers (no. and quantity) or just a float (price). That is

#include <stdio.h>

#define ITEMS 300
int main(void)
{
  float price[ITEMS];
  int items = 0;

  int item_no;
  int item_qty;

  char line[80];

  while ( fgets(line, sizeof(line), stdin) && items < ITEMS )
  {
    if ( sscanf(line, "%d %d", &item_no, &item_qty) == 2)
    {
      if  (item_no < items)
        printf("item n. %d, item quatity %d, price = %f\n", item_no, item_qty, price[item_no] * item_qty);
    }
    else
    {
      if ( sscanf(line, "%f", &price[items]) == 1)
        ++items;
    }
  }
  return 0;
}


想想你将如何在商店里这样做。

Think about how you would do this in a shop.
You: I would like to buy some widgets.
Shopkeeper: Certainly madam, which size?
You: the big ones.
Shopkeeper: And how many would you like?
... etc.





所以你需要做类似的事情。



So you need to do something similar.

Print a message asking for some information.
Read the user's response.
Check that what they have entered is valid.
Repeat the above for each item of information.
Do the various calculations.
Print the results.