Liste des Groupes | Revenir à cl c |
Groovy hepcat DFS was jivin' in comp.lang.c on Wed, 19 Mar 2025 03:42https://c-faq.com/
pm. It's a cool scene! Dig it.
On 3/18/2025 11:26 PM, Keith Thompson wrote:Normally I'd say take care with scanf(). But in this case, since theDFS <nospam@dfs.com> writes:>There's your problem.>
>
https://cses.fi/problemset/text/2433
>
"In all problems you should read input from standard input and write
output to standard output."
ha! It usually helps to read the instructions first.
>The autotester expects your program to read arguments from stdin, not>
from command line arguments.
>
It probably passes no arguments to your program, so argv[1] is a null
pointer. It's likely your program compiles (assuming the NBSP
characters were added during posting) and crashes at runtime,
producing no output.
I KNEW clc would come through!
>
Pretty easy fixes:
>
1 use scanf()
program is intended to be executed in an automated environment, it
should be fine.
The reason scanf() can be a bit iffy is that you can't control what a
user will enter. If you search Google or Duck Duck Go for "comp.lang.c
faq" you can find more information on this and other issues. (The FAQ
is still out there, people..., somewhere...)
It's a 'special case' because n is already 1.2 update int to longThe problem definition doesn't mention any special case. You should, I
3 handle special case of n = 1
think, treat 1 like any other number. So the output for 1 should be
1 4 2 1
Cool.4 instead of collecting the results in a char variable, I printYep, that's a more usual approach.
them as they're calculated
Another suggestion I have is to use a separate function to do part of
the work. But it's not vital.
Also, since the specification says that only positive numbers are to
be accepted, it makes sense (to me, at least) to use an unsigned type
for n.
One more thing: using while(1){...break;} is a bit pointless. You can
use do{...}while(1 != n) instead.
Here's my solution, for what it's worth:
#include <stdio.h>
unsigned long weird(unsigned long n)
{
printf("%lu", n);
if(n & 1)
{
/* Odd - multiply by 3 & add 1. */
n = n * 3 + 1;
}
else
{
/* Even - divide by 2. */
n /= 2;
}
return n;
}
int main(void)
{
unsigned long n;
/* Get n from stdin. */
scanf("%lu", &n);
/* Now feed it to the algorithm. */
do
{
n = weird(n);
putchar(' ');
} while(1 != n);
printf("%lu\n", n);
return 0;
}
Les messages affichés proviennent d'usenet.