【问题标题】:Read two whole numbers and find all the positive multiples of the first that are less than the second读取两个整数并找出第一个小于第二个的所有正倍数
【发布时间】:2014-06-10 03:31:46
【问题描述】:

问题是这样的:“读取两个整数 a 和 b。a 介于 1 和 10 之间,b 介于 20 和 50 之间。程序必须打印生成的值,还必须打印存在于 1 之间的倍数和 b.

我写的程序是这样的:

#include <stdio.h>    
#include <conio.h>

int main()
{
    int a, b;
    int num = 0;
    printf("\nIntroduce the first number:");
    scanf("%d", &a);
    printf("\nIntroduce the second number:");
    scanf("%d", &b);

    for(a = 1; a <= 10; a++)
    {
        for(b = 20; b <= 50; b++)
        {
            while(a < b)
            num = a * a;
        }
        printf("\n%d",num);
    }

    getch();
    return 0;
}

那是我写的程序,但我错了。我必须使用 for 函数,但我不知道如何使程序工作。

感谢所有帮助!

【问题讨论】:

  • 对不起,我没听懂你的问题。任何数的倍数都是无限的。例如,2 的倍数是无限的。问题是什么?
  • 期望的输出是什么?你能举个例子,如果程序应该工作,它应该用 9 和 25 打印出什么
  • 哦,好的。举个例子:a=4 和 b=37 那么答案应该是 4 到 37 的倍数,就像这样:4,8,12,16,20,24,28,32,36。所以最终的输出应该是那个序列。对不起,如果我让你感到困惑。
  • 你有一个逻辑问题而不是编程问题。

标签: c function for-loop structure


【解决方案1】:

在这里,这将打印出您想要的输出。

#include <stdio.h>
#include <conio.h>

int main() {
  int a,b;
  int i;
  int num=0;

  printf("\nIntroduce the first number:");
  scanf("%d",&a);

  printf("\nIntroduce the second number:");
  scanf("%d",&b);

  for(i = 1; ;i++) {
    num = a * i;
    if(num > b)
        break;
    printf("%d ", num);
  }

  return 0;
}

我没有包括错误处理的东西,比如如果用户输入的值超出了指定的输入范围,你应该再次要求它。我建议如果你想让你的程序更健壮,你应该包括它。

如果您还有其他问题,请询问:D

【讨论】:

  • 非常感谢!这就是我需要的。如果我没有正确表达这个问题,也很抱歉。
【解决方案2】:

将 printf 放在 num =a*a 之后的第二个循环中

#include <stdio.h>    
#include <conio.h>
int main()
{
int a,b;
int num=0;
printf("\nIntroduce the first number:");
scanf("%d",&a);
printf("\nIntroduce the second number:");
scanf("%d",&b);
  for(a=1;a<=10;a++)
   {
   for(b=20;b<=50;b++)
   {
       while(a<b)
        num=a*a;
        printf("\n%d",num);
 }

 }
getch();
return 0;
  }

【讨论】:

  • 这是什么逻辑?为什么 a 总是从 a =1 循环。为什么是数字的平方?问题是找到给定数字范围之间的倍数。
  • 我的错误使用 num =a*b
猜你喜欢
  • 1970-01-01
  • 2013-01-06
  • 1970-01-01
  • 2019-08-07
  • 1970-01-01
  • 1970-01-01
  • 2013-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多