带char和整数的数组

时间:2014-04-12 00:49:29

标签: c arrays

我刚开始用C语言学习数组。
1。试图打印出项目名称和价格,但得到错误,虽然编译没有错误给出,但当我运行它给出错误。
我在这里做错了什么?

这是我的代码

   #include<stdio.h>

    int main(void){

        float p[7]={0.55,0.8,1,1.2,0.95,0.4,0.6};
        int i=1;

        printf("%s%10s\n","#Item","ItemName");
            for(i=1;i<8;i++){

                printf("%s%13f0.2\n",i,p[i]);
    }

        return 0;

    }

2.我如何列出姓名?我试过char,但效果不好。

char n[10]={'Water','Cola','Fanta','Chokolate','Biscuit','Gum','Candy'};

这给出了errl4 14 C:\ Users \ Erdene \ Desktop \ turshilt.c

[Warning] character constant too long for its type

如果我改变n [100]我如何列出编号和定价?

喜欢上市数字和数字旁边的项目和价格。
任何建议?感谢

3 个答案:

答案 0 :(得分:1)

你必须明白,你拥有的char类型值数组与字符串数组之间存在差异。

您使用数字或单引号表示单个字符值

char bar = 65;
char foo = 'A';

这两个都是相同的值。 char只能存储一个字符的信息,大小受一个字节的限制。

当你声明一串char s使用双引号时

char string[100] = "Hello!";

作为Jim Lewis发布的替代方法,如果您在编译时知道,可以使用常量大小的数组。在这种情况下,您需要指定除最外层级别之外的所有内容。

// This will store as many 19 letter words, as you specify in the declaration
char strings[][20] = {"One", "word", "two", "words"};
// The index starts at zero
printf("%s\n", strings[0]); // -> One
printf("%s\n", strings[1]); // -> word
printf("%s\n", strings[2]); // -> two
printf("%s\n", strings[3]); // -> words
printf("%s\n", strings[4]); // -> ERROR - out of bounds

答案 1 :(得分:1)

float p[7]={0.55,0.8,1,1.2,0.95,0.4,0.6};

C中的数组从0开始编入索引,因此for循环应为

for(i=0;i<7;i++) { ... }

对于你问题的其他部分:

char n[10]={'Water','Cola','Fanta','Chokolate','Biscuit','Gum','Candy'};

你应该对字符串使用双引号(单引号用于字符 常量)。 n应该是一个包含十个指针的数组,而不是十个字符, 并且最好使数组大小与初始化程序的数量相同:

char *n[7]={"Water","Cola","Fanta","Chokolate","Biscuit","Gum","Candy"};

答案 2 :(得分:0)

阅读其他答案以解释原因。请阅读下面的示例,以获取如何执行此操作的完整示例。

#include <stdio.h>

int main(void){

    // array sizes do not need to be explicitly set when initialized this way
    char *n[]={"Water","Cola","Fanta","Chokolate","Biscuit","Gum","Candy"};
    float p[]={0.55,0.8,1,1.2,0.95,0.4,0.6};
    int i;
    // calculate array length, so can change array length without breaking code
    int len = sizeof(n)/sizeof(*n);

    // tinker with printf if you want to make the columns wider, etc.
    printf("%s%11s%9s\n", "Item #", "Item Name", "Price");
    for(i = 0; i < len; i++) {
        printf("%6d  %-10s%8.2f\n", i + 1, n[i], p[i]);
    }
    return 0;
}
相关问题