C语言程序输入优化求助:无需空格拆分成绩至f与l变量
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 inf),45 % 10 = 5(stored inl) - When you input
100:100 / 10 = 10(stored inf),100 % 10 = 0(stored inl) - Even for a single-digit input like
7:7 /10 =0(stored inf),7%10=7(stored inl)
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

