需要C程序练习的帮助 [英] Need help with a C program exercise

查看:76
本文介绍了需要C程序练习的帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我现在正在编写一个类似订单发票的程序。用户输入物品的价格和他想要的物品数量。



示例

1.42 - 价格

2.25

30.21

0 200 -Item Number and Quatity

1 400

2 100



所以我的问题是如何区分价格输入和项目编号,数量输入?



我尝试过:



我写过



So I'm currently writing a program that sort of functions like an order invoice. The user inputs the price of the items and the number of items he wants.

Example
1.42 - Price
2.25
30.21
0 200 -Item Number and Quatity
1 400
2 100

So my problem is how do I differentiate between the Price inputs and Item Number, Quantity input?

What I have tried:

I have written

#include <stdio.h>

int main(void)
{
	
	int item ;
	float value;
	float price[300];
	for (item = 0;( Missing Condition to exit);item++)
	{
		scanf("%f",&value);	
		price[item]=value;
		      
			
	
	}	
	
	
}	





适用于输入商品价格。

我不知道如何过渡到商品编号和数量输入。



Which works for inputting the item price.
I do not know how to transition to Item Number and Quantity inputs.

推荐答案

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

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.


这篇关于需要C程序练习的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆