You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修正C语言成绩平均值代码的序数词显示问题(保持行数不变)

Fixing Ordinal Suffixes (1st/2nd/3rd instead of 1th/2th/3th) Without Adding Code Lines

Got it, let's tackle this ordinal suffix issue while keeping your code line count exactly the same and making minimal changes.

The Problem

Your original code uses %dth in the printf statement, but since i starts at 0, you're getting 0th (which is wrong) plus incorrect suffixes for 2 and 3. We need to adjust the numbering to start at 1 and swap the fixed "th" with dynamic suffixes.

Modified Code

#include<stdio.h>
int main() {
    int marks[10],sum=0,i;
    float avg;
    for(i=0;i<=9;i++) {
        printf("Enter the next element to be inserted into the array\n");
        scanf("%d",&marks[i]);
    }
    for(i=0;i<=9;i++) {
        sum = sum+marks[i];
        printf("mark %d%s=%d\nsum=%d\n",i+1, (i+1)==1?"st":(i+1)==2?"nd":(i+1)==3?"rd":"th", marks[i], sum);
    }
    avg = sum/10;
    printf("The average of the 10 elements of the array is %f",avg);
}

What Changed

We only modified the printf line in the second loop:

  1. Replaced i with i+1 to show the correct 1-10 numbering instead of 0-9.
  2. Swapped the fixed "th" with a nested ternary operator that checks the number:
    • If it's 1 → use "st"
    • If it's 2 → use "nd"
    • If it's 3 → use "rd"
    • For all other numbers (4-10) → use "th"

This approach keeps your code line count identical, avoids adding extra variables or conditional blocks, and fixes the suffix display issue perfectly.

内容的提问来源于stack exchange,提问作者coderredoc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:12:27