我正在尝试使该程序显示为每个输入的名称输入的件数以及计算价格。目前,该程序仅显示最后输入的名称,件数为0,价格为0.00,与我输入的件数无关。 (我对最终的for循环完全不确定,因此它显示为灰色。)
我主要是在寻找朝着正确方向发展的纽带,对此我还很陌生,很容易思考问题,使自己变得更难。这是代码,我感谢任何提示。
#include <stdio.h>
#define SIZE 20
int main()
{
int total=0,comp, ctr=0;
char name[SIZE];
float price;
printf("Please enter the number of pieces: ");
scanf("%d", &comp);
while( comp != 0)
{
// ctr = ctr + 1;
printf("Please enter the name: ");
scanf("%19s", name);
printf("Please enter the number of pieces: ");
scanf("%d", &comp);
if ( comp > 0 && comp < 200)
{
price = comp * .50;
}
if ( comp > 199 && comp < 400)
{
price = comp * .55;
}
if ( comp > 400 && comp < 600)
{
price = comp * .60;
}
if ( comp > 600)
{
price = comp * .65;
}
ctr = ctr + 1;
}
printf("%s%13s%13s\n","Name", "Pieces", "Price");
//for ( name[7] =0; name[7] <= 7; ++name[7]);
// {
printf("%s%12d%12.2f\n", name, comp, price);
// }
return 0;
}
答案 0 :(得分:0)
我可能会误解您正在尝试使用此逻辑做什么,但是基于我在代码中看到的内容,这就是为什么您看到所看到的输出的原因:
尝试以下代码。它可能无法完全满足您的需求,但我认为它将使您更进一步:
#include <stdio.h>
#define NSTRINGS 10 // Max number of named items
#define MAXSTRING 20 // Max name string length
int main()
{
int total=0, comp[NSTRINGS];
char name[NSTRINGS][MAXSTRING];
float price[NSTRINGS];
for(int i = 0; i < NSTRINGS; i++) {
printf("Please enter the number of pieces: ");
scanf("%d", &comp[i]);
if(comp[i] == 0) {
break;
}
printf("Please enter the name: ");
scanf("%19s", name[i]);
if ( comp[i] > 0 && comp[i] < 200)
{
price[i] = comp[i] * .50;
}
if ( comp[i] > 199 && comp[i] < 400)
{
price[i] = comp[i] * .55;
}
if ( comp[i] > 400 && comp[i] < 600)
{
price[i] = comp[i] * .60;
}
if ( comp[i] > 600)
{
price[i] = comp[i] * .65;
}
}
printf("%s%13s%13s\n","Name", "Pieces", "Price");
for(int i = 0; i < NSTRINGS && comp[i] !=0; i++) {
printf("%s%12d%12.2f\n", name[i], comp[i], price[i]);
}
return 0;
}
然后输出看起来像这样:
$ ./a.out
Please enter the number of pieces: 20
Please enter the name: Test1
Please enter the number of pieces: 456
Please enter the name: Test2
Please enter the number of pieces: 698
Please enter the name: Test3
Please enter the number of pieces: 0
Name Pieces Price
Test1 20 10.00
Test2 456 273.60
Test3 698 453.70
$
希望这会有所帮助。