Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基本C程序设计_C - Fatal编程技术网

基本C程序设计

基本C程序设计,c,C,我正在尝试编写一个程序,给定一定数量的输入,它将输出列出的输入的乘积(只计算0-9的输入,忽略其他输入) 例如: input:345 would result output: 60, or another example would be, input: 3t4 and output: 12 我已经尝试了很多次,这就是我一直坚持的: #include <stdio.h> main(){ int c,i; c = getchar(); i = 1; while (c!= '\

我正在尝试编写一个程序,给定一定数量的输入,它将输出列出的输入的乘积(只计算0-9的输入,忽略其他输入)

例如:

input:345 would result output: 60, or another example would be, input: 3t4 and output: 12
我已经尝试了很多次,这就是我一直坚持的:

#include <stdio.h>


main(){

int c,i;

c = getchar();
i = 1;
while (c!= '\n'){
        if (c>=48 && c<=57){
          i=c*i;
          c=getchar();
        }
}
printf("%d",i);
}
#包括
main(){
int c,i;
c=getchar();
i=1;
而(c!='\n'){

如果(c>=48&&c代码中存在两个问题

  • 每次程序遇到非数字字符后,它都不会从输入中进一步读取。它读取相同的字符。因此
    c=getchar()
    应该在
    if
    块之外
  • char
    变量
    c
    进行乘法运算。应将其转换为实际数字,然后再进行乘法运算。在代码中,您将乘以其ascii值。因此
    (c-48)*i
    而不是
    c*i
使用
i=(c-48)*i;
而不是
i=c*i
。因此,更改的程序将是:

#include <stdio.h>

main(){

int c,i;

c = getchar();
i = 1;
while (c!= '$'){
//    printf("%c\n", c);
        if (c>=48 && c<=57){
          i=(c-48)*i;
        }
        c=getchar();
}
printf("%d",i);
}
#包括
main(){
int c,i;
c=getchar();
i=1;
而(c!=“$”){
//printf(“%c\n”,c);
如果(c>=48&&c
inti,c;
i=1;
而(i){
c=getchar();
如果(c=='\n')
{
打破
}
如果(c<48 | | c>57)
{
i=-1;
打破
}
i=i*(c-48);
}
如果(i==-1)
{
printf(“错误。未输入数字\n\n”);
}
否则{
printf(“%d\n\n”,i);
}

你的问题是什么?你不应该乘以
c-'0'
?对于开始,停止使用魔法数字
48
57
。分别用
'0'
'9'
替换它们。并添加
c!=EOF
检查你的
状态。或者使用标准库函数
isdigit
或至少如果((c>='0')&&(我怀疑初学者甚至不知道什么是幻数:试试代码。它不起作用。它接受一个数字并打印出来。@RikayanBandyopadhyay,用更正编辑,检查它now@Rikayan班迪奥·帕迪亚:OP把所有的输入都放在一行上;我猜他想在newline上退出。在我看来,对于一个一次性节目来说,似乎很优雅。@RikayanBandyopadhyay,噢,如果您使用的是多行输入,那么您不能使用while(c!='\n'),您必须使用其他字符,例如while(c!='$')){…例如,$是输入结束标记。但是,根据您的原始示例,换行符检查将起作用,您的原始示例是使用单行输入,输入:345将导致输出:60,或者另一个示例是输入:3t4和输出:12@RikayanBandyopadhyay,好吧,如果你接受,你可以随时投票如果愿意,请接受已编辑的答案
int i,c;

i = 1;

while (i){

    c=getchar();

    if(c == '\n')
    {
        break;
    }

    if (c < 48 || c > 57)
    {
        i = -1;
        break;
    }

    i = i * (c-48);

}

if (i == -1)
{
    printf("Error. Non-Number Entered\n\n");
}

else {

    printf("%d\n\n",i);

}