Jump to content
  • Hello visitors, welcome to the Hacker World Forum!

    Red Team 1949  (formerly CHT Attack and Defense Team) In this rapidly changing Internet era, we maintain our original intention and create the best community to jointly exchange network technologies. You can obtain hacker attack and defense skills and knowledge in the forum, or you can join our Telegram communication group to discuss and communicate in real time. All kinds of advertisements are prohibited in the forum. Please register as a registered user to check our usage and privacy policy. Thank you for your cooperation.

    TheHackerWorld Official

C语言——控制语句(三元运算符)

 Share


NedK7

Recommended Posts

 

三元运算符格式:

Exp1 ? Exp2 : Exp3;

? 表达式的值是由 Exp1 决定的。如果 Exp1 为真,则计算 Exp2 的值,结果即为整个表达式的值。如果 Exp1 为假,则计算 Exp3 的值,结果即为整个表达式的值。

示例代码:

#include<stdio.h>
int main()
{
    /*三元运算符*/
    int num;
    printf("输入一个整数: ");
    scanf("%d",&num);//获取用户输入的信息
    (num%2==0) ? printf("%d是偶数",num) : printf("%d是奇数",num);
    return 0;
}

运行结果:

输入一个整数: 6
6是偶数

 

 

例子:

#include <stdio.h>
int main()
{
    int A=10;
    int B=20;
    char buy;
    int sum,number;
    printf("商品清单:\n A 商品10元/个 \n B 商品20元/个 \n");
    printf("请输入要购买的商品(A 或 B):");
    scanf("%c",&buy);
    printf("请输入购买数量:");
    scanf("%d",&number);
    sum=((buy=='A') ? (A*number) : (B*number)) ;
    printf("\n购买的%d个%c商品共计%d元。\n",number,buy,sum);
    return 0;
}

运行结果:

商品清单:
 A 商品10元/个
 B 商品20元/个
请输入要购买的商品(A  B):B
请输入购买数量:2

购买的2B商品共计40元。
Link to post
Link to comment
Share on other sites

 Share

discussion group

discussion group

    You don't have permission to chat.
    • Recently Browsing   0 members

      • No registered users viewing this page.
    ×
    ×
    • Create New...