c - 如何将 printf 中写入的值调用到另一个 printf

标签 c printf scanf

我对编程很陌生。

我正在尝试编写一个程序,从数组中调用水果的价格。但我希望代码在写价格之前也写水果的名称。如果我键入 2,如何使输出为“Orange price : 10”而不仅仅是 price : 10。

#include <stdio.h>
int main(void)
{
    int i;
    int a[3] = { 5,10,15 };
    printf("1) Apple");
    printf("2) Orange");
    printf("3) grape");

    while (1) {

        printf("Which fruit would u like : ");

        scanf("%d", &i);//Enter the fruit number
        if (i <= 0 || i >= 4) {
            printf("\nPlease use the correct number :");
        }
         else {
            printf("Price :%d", a[i]);
            break;
        }
    }
}

最佳答案

只需定义一个名称数组,如

int a[3] = { 5,10,15 };
const char *fruit[] = { "Apple", "Orange", "grape" };

并在 printf 调用中使用它。例如

printf( "%s price: %d", fruit[i], a[i] );

还有这些语句

printf("1) Apple");
printf("2) Orange");
printf("3) grape");

可以改写成

for ( i = 0; i < N; i++ )
{
    printf( "%zu) %s\n", i + 1, fruit[i] );
}

考虑到这个 if 语句

if (i <= 0 || i >= 4) {

不正确。必须有

if (i < 0 || i > 2) {

使用魔数(Magic Number)也是个坏主意。

你可以改写。

enum { N = 3 };
int a[N] = { 5,10,15 };
const char *fruit[N] = { "Apple", "Orange", "grape" };

size_t i = 0;

//...

scanf("%zu", &i);//Enter the fruit number
if ( !( i < N ) ) {

关于c - 如何将 printf 中写入的值调用到另一个 printf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58171405/

相关文章:

c - printf 语句未在 netbean 中的 scanf 语句之前执行

复利计算器 - C

复制二进制文件的内容

c - 如何在 C 语言中分隔括号之间的术语并列出它们

c - 在指针数组中输入字符串

c - sprintf 会删除它上次写入缓冲区时添加的最后一个空字符吗?

c - 如何访问字符数组的第一个字符?

bash - 管道 seq 到 printf 以进行数字格式化

c - 稍后在程序中不会遵循用户定义的值

c - 在 C 中使用 scanf 检测新行