You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.8 KiB
55 lines
1.8 KiB
#include <unistd.h>
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
#include <stdlib.h>
|
|
|
|
// 假设的 Fibonacci 函数实现
|
|
unsigned long int fib(unsigned long int n) {
|
|
if (n <= 1) return n;
|
|
return fib(n - 1) + fib(n - 2);
|
|
}
|
|
|
|
int main() {
|
|
char buffer[1024]; // Buffer to store input data
|
|
|
|
// Read data from stdin into buffer
|
|
ssize_t bytes_read = read(0, buffer, sizeof(buffer) - 1);
|
|
if (bytes_read < 0) {
|
|
perror("Error reading input");
|
|
return 1;
|
|
}
|
|
buffer[bytes_read] = '\0';
|
|
|
|
// Remove potential newline character at the end of the input
|
|
if (bytes_read > 0 && (buffer[bytes_read - 1] == '\n' || buffer[bytes_read - 1] == '\r')) {
|
|
buffer[bytes_read - 1] = '\0';
|
|
}
|
|
|
|
unsigned long int num1, num2;
|
|
char *line = strtok(buffer, "&");
|
|
char *second_part = strtok(NULL, "&"); // Assume the rest of the string is the second number
|
|
|
|
if (line && sscanf(line, "%lu", &num1) == 1 &&
|
|
second_part && sscanf(second_part, "%lu", &num2) == 1) {
|
|
// Calculate Fibonacci numbers and their sum
|
|
unsigned long int fib1 = fib(num1);
|
|
unsigned long int fib2 = fib(num2);
|
|
unsigned long int sum = fib1 + fib2;
|
|
|
|
// Prepare output string
|
|
char output[1024];
|
|
int len = snprintf(output, sizeof(output), "Fibonacci(%lu) + Fibonacci(%lu) = %lu + %lu = %lu\n", num1, num2, fib1, fib2, sum);
|
|
|
|
// Write to stdout
|
|
write(1, output, len);
|
|
} else {
|
|
const char *error_msg = "Invalid input. Please enter two numbers separated by '&'. Your input was: ";
|
|
char output_buffer[2048]; // Buffer to hold the error message and user input
|
|
int len = snprintf(output_buffer, sizeof(output_buffer), "%s%s\n", error_msg, buffer);
|
|
write(1, output_buffer, len);
|
|
return 1;
|
|
}
|
|
|
|
return 0;
|
|
}
|