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

C语言程序输入优化求助:无需空格拆分成绩至f与l变量

Solution: Split Input Grade Without Spaces

Got it, let's fix this problem so you don't have to input spaces anymore! The core issue with your original code is that scanf("%d %d") expects two separate integers separated by whitespace. Instead, we can read the entire grade as a single number first, then split it into the required parts using basic math operations—super straightforward.

Approach 1: Mathematical Splitting (Simplest)

This method works for any grade value (1-digit, 2-digit, 3-digit like 100) by extracting the leading digits (for f) and the last digit (for l) using division and modulus operations:

  • f = entire grade divided by 10 (integer division truncates the last digit)
  • l = entire grade modulo 10 (gives the remainder, which is the last digit)

Here's the modified code:

#include <stdio.h> 

int main(void) { 
    int grade, f, l; 
    printf("Enter numerical grade: ");
    // Read the entire grade as one integer
    scanf("%d", &grade); 
    // Split into f and l
    f = grade / 10; 
    l = grade % 10; 

    // You can continue with your original logic using f and l here
    printf("f = %d, l = %d\n", f, l); 
    return 0; 
}

How it works:

  • When you input 45: 45 / 10 = 4 (stored in f), 45 % 10 = 5 (stored in l)
  • When you input 100: 100 / 10 = 10 (stored in f), 100 % 10 = 0 (stored in l)
  • Even for a single-digit input like 7: 7 /10 =0 (stored in f), 7%10=7 (stored in l)

Approach 2: String-Based Splitting (More Flexible)

If you want to handle edge cases like non-numeric input or very long grades, you can read the input as a string and split it manually:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void) {
    char input[10];
    int f, l;
    printf("Enter numerical grade: ");
    scanf("%s", input);

    int length = strlen(input);
    if (length == 1) {
        f = 0;
        l = input[0] - '0'; // Convert char to integer
    } else {
        // Extract all characters except the last for f
        char f_str[9];
        strncpy(f_str, input, length - 1);
        f_str[length - 1] = '\0'; // Null-terminate the substring
        f = atoi(f_str); // Convert substring to integer
        l = input[length - 1] - '0'; // Get the last digit
    }

    printf("f = %d, l = %d\n", f, l);
    return 0;
}

This method parses the input as text, giving you more control over splitting logic, but the mathematical approach is far simpler for your specific use case.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:52:03