gpt4 book ai didi

c - 将 % 的值拆分为多个字符

转载 作者:行者123 更新时间:2023-11-30 17:10:27 26 4
gpt4 key购买 nike

我收到了一个赋值问题,到目前为止我已经设法解决了所有问题,除了在几个(输入确定的)字符之间分割余数值之外。任何帮助将不胜感激。作为引用,我的作业问题是:

“如果你看报纸,你会发现文字是对齐的,适合各栏。编写一个程序,读取报纸中栏的宽度,然后读取一行文本。对齐文本行适合该宽度的列。当您的程序运行时,屏幕应如下所示:

Enter the width of the column: 40Enter a line of text: Good morning how are you?12345678901234567890123456789012345678901234567890...Good     morning     how     are    you?

The justification is done by counting the number of gaps in the text. In the above example, there are 4 gaps. Then each gap must have spaces added to it. The number of extra spaces must be shared out as evenly as possible. In the above example, the first three gaps have 5 spaces each and the last gap has 4 spaces.

Notes:

  1. If the text is longer than the column then you must report an error – don't try and break it into two lines!
  2. Assume that the text will have more than one word in it.
  3. Note the header line consisting of 123456789012345678.... this is useful to check your result. You can make this header line as long as you like – 70 spaces would be a useful length.

"

And my code so far is:

int main() {
//input column width
printf("Enter the width of the column: ");
int column;
scanf("%d", &column);

//input text line
printf("Enter a line of text: ");
char string[80];
getchar();
gets(string);

//print 1234567890 column header
int y = 1,x = 0;
while(x < column){
if(y > 9){
y = 0;
}
printf("%d", y);
y++;
x++;
}
printf("\n");

//count spaces
int i = 0;
int space_count = 0;
while(string[i] != '\0'){
if(string[i] == 0x20){
space_count++;
}
//printf("%c", string[i]);
i++;
}

//work out variables
int string_length = i;
int remainder_space = (column - string_length);
int space_power = (remainder_space / space_count);
//int oddremainder = (space_count % remainder_space) ;
//space_power = (space_power + oddremainder);
//if
//remainder %

//insert column width check
if(string_length > column)
{
printf("Text is too long. Shouldn't be more than %dcharacters\n",
column);
return 1;
}
//output
i = 0;
while(string[i] != '\0'){
if(string[i] == 0x20){
for(x = 0; x < space_power; x++){
printf("%c", 0x20);
}
}
printf("%c", string[i]);
i++;
}

如果这不是提问的正确方式,我很抱歉,我的大脑已经崩溃了,我无法理解这个问题。任何正确方向的指示或讨论将不胜感激。

最佳答案

让我们看一下示例。它有 19 个空格需要填补 4 个空白。如果您的代码像这样运行,则 space_power 的值将为 4 (int(19/4)),最后会留下 3 个空格。您需要跟踪 19 % 4,即。 3 个额外空格。

因此,保留一个计数,最初等于 3。然后,当该计数大于 0 时,打印一个额外的空格以及所有 space_power 数量的空格。每次打印一个单词时减少计数。

你的代码将是这样的:

count = remainder_space % space_count;

和输出 block :

i = 0;
while(string[i] != '\0'){
int k = count > 0 ? 1 : 0;
if(string[i] == 0x20){
for(x = 0; x < space_power + k; x++){
printf("%c", 0x20);
}
count--;
}
printf("%c", string[i]);
i++;
}

关于c - 将 % 的值拆分为多个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32861356/

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