如何修正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:
- Replaced
iwithi+1to show the correct 1-10 numbering instead of 0-9. - 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"
- If it's 1 → use
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
相关产品推荐
相关产品推荐

