gpt4 book ai didi

C 程序数组超过 1 个字

转载 作者:行者123 更新时间:2023-11-30 20:11:49 25 4
gpt4 key购买 nike

这个问题来自 HackerRank,我尝试使用 %[^\n]s 来表示长单词。但是,输出继续产生 .0

如何将 %[^\n]s 替换为其他内容以使字符串接收输入?

这是输入:

12
4.0
is the best place to learn and practice coding!

这是我的输出:

16
8.0
HackerRank .0

这是预期的输出:

16
8.0
HackerRank is the best place to learn and practice coding!

这是我的完整代码,如您所见,它无法识别 %[^\n]s。如何解决这个问题呢?谢谢。

完整代码:

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

int main() {
int i = 4;
double d = 4.0;
char s[] = "HackerRank ";

// Declare second niteger, double, and String variables.
int value1, sum1, value2;
double e = 2.0, sum2;
char t[30];

// Read and save an integer, double, and String to your variables.
scanf(" %d", &value1);
scanf("%d", &value2);
scanf("%[^\n]s", t); //** POINT OF INTEREST **

// Print the sum of both integer variables on a new line.
sum1 = value1 + i;
printf("%d\n", sum1);

// Print the sum of the double variables on a new line.
sum2 = d * e;
printf("%.1lf\n", sum2);

// Concatenate and print the String variables on a new line
// The 's' variable above should be printed first.
printf("%s %s", s, t);

return 0;
}

最佳答案

考虑到您的输入输出示例,我修改了您的代码,如下所示:

char t[256]; // the string "is the best place to learn and practice coding!" MUST FIT!!!
...
scanf("%d", &value1);
scanf("%lf", &d); // NOT %d, %lf !!! &d or &e - I don't know - depends on you
scanf("\n%[^\n]", &t);
...
printf("%s%s", s, t); // you don't need a space, since your "s" already contains it.

对我来说效果很好。

UPD:现在它实际上工作得很好。

关于C 程序数组超过 1 个字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39044766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com